我已经尝试使用Python客户端,一切正常,但是使用C ++客户端,数据包无法到达Python服务器。
客户端和服务器都在同一台计算机上运行。我也禁用了Windows防火墙并获得了相同的结果。 Python服务器正在侦听端口50000.对于IP地址,我尝试过localhost和127.0.0.1
Python服务器代码:
import socket
HOST, PORT = "localhost", 50000
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, PORT))
while 1:
data, info = s.recvfrom(4096)
print 'got' + repr(data)
C ++客户端代码:
#include <string>
#include <WinSock2.h>
#include <Ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main() {
const char* pkt = "Message to be sent";
const char* host = "localhost"; // tried 127.0.0.1 here as well
sockaddr_in dest;
sockaddr_in local;
WSAData data;
WSAStartup(MAKEWORD(2, 2), &data);
char srcAddr[INET_ADDRSTRLEN];
char destAddr[INET_ADDRSTRLEN];
local.sin_family = AF_INET;
local.sin_addr.s_addr = inet_pton(AF_INET, host, srcAddr);
local.sin_port = htons(0);
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_pton(AF_INET, host, destAddr);
dest.sin_port = htons(50000);
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
bind(s, (sockaddr *)&local, sizeof(local));
sendto(s, pkt, sizeof(pkt), 0, (sockaddr *)&dest, sizeof(dest));
return 0;
}