从网络C ++接收数据

时间:2017-04-06 14:44:27

标签: c++ python-2.7 sockets networking

我有一个python函数通过数据克socket在网络上发送数据。在接收端我必须使用c ++接收数据但是接收者不能接收任何有意义的数据。应该用什么以确切的格式获取字符串?

Python代码

def send(self, command):
        segments = command.split() # split command on spaces
        if len(segments) < 5 or segments[1] not in self.hosts or segments[2] not in self.hosts: # sanity check
            print('invalid arguments')
            return
        else:
            h1 = map(int, segments[1].split('.'))# segment 1 contains a IP address
            h2 = map(int, segments[2].split('.'))# segment 2 contains an IP address
            fmt = '4s4B4Bh' + segments[3] + 's'# segemt 3 is string length segment 4 is a string
            buf = struct.pack(fmt, segments[0], h1[0], h1[1], h1[2], h1[3], h2[0], h2[1], h2[2], h2[3], int(segments[3]), ' '.join(segments[4:]))
            print('sending to {0}'.format(segments[1])) # print a message before sending to source
            self.s.sendto(buf, (segments[1], self.port)) # send to source
            #self.s.sendto(command, (segments[1], self.port)) # send to source

C ++代码

bytes_received = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*) &client_address, &addrlen);
        //print(buffer);
        if(bytes_received==-1)
        {
            perror("recvfrom");
            printf("error %s\n",strerror(errno));
        }

        printf("[%s:%hu]: %s \n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port), buffer);

所有套接字都已正确创建

1 个答案:

答案 0 :(得分:0)

If you receive something like "send ???????" I'd expect encoding problems during sending. '?' is 0x3F (dec 63) which usually comes from characters out of basic ASCII (less then 127) table. I'm not familiar with python, but can you ensure you use proper (e.g. UTF-8, for sure not UTF-16/32 and perhaps not ASCII) encoding while transforming python string into byte array?