我开发了一个应用程序,其中客户端和服务器可以使用 UDP 套接字相互通信。我在客户端使用了回环地址,在服务器端使用了 INADDR_ANY。该程序在同一台机器上运行良好。但是当我尝试从另一台机器上运行客户端时,通信失败了。这是代码片段: 服务器:
#define PORT 8888 //The port on which to listen for incoming data
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
exit(EXIT_FAILURE);
}
///Create a socket///
if((socketIdentifier = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
{
//"Socket not created"
}
///Socket Created///
///Prepare the sockaddr_in structure///
serverSocket.sin_family = AF_INET;
serverSocket.sin_addr.s_addr = INADDR_ANY;
serverSocket.sin_port = htons( PORT );
///Bind///
if( bind(socketIdentifier ,(struct sockaddr *)&serverSocket , sizeof(serverSocket)) == SOCKET_ERROR)
{
//"Bind Failed"
}
///Bind Done///
if((recv_len = recvfrom(socketIdentifier, receiveBuffer, sizeof(receiveBuffer), 0, (struct sockaddr *) &clientSocket, &clientSocketLength)) == SOCKET_ERROR)
{
"Could not Receive Data"
}
hDeviceContext = BeginPaint(AH_Glb_windowHandle, &ps );
TextOut(GetDC(AH_Glb_windowHandle),10,10+i,receiveBuffer,recv_len);
EndPaint( AH_Glb_windowHandle, &ps );
客户:
#define PORT 8888 //The port on which to listen for incoming data
#define SERVER "58.65.172.11" //ip address of udp server
///Initialise winsock///
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
//Socket Initialization Failed///
exit(EXIT_FAILURE);
}
///create socket///
if ((socketIdentifier=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
{
///Socket Creation Failed///
exit(EXIT_FAILURE);
}
///setup address structure///
memset((char *) &connectedSocket, 0, sizeof(connectedSocket));
connectedSocket.sin_family = AF_INET;
connectedSocket.sin_port = htons(PORT);
connectedSocket.sin_addr.S_un.S_addr = inet_addr(SERVER);
if (sendto(socketIdentifier,sendBuffer,strlen(sendBuffer) , 0 , (struct sockaddr *) &connectedSocket, sizeof(connectedSocket)) == SOCKET_ERROR)
{
MessageBox(NULL,
"Sending Failed",
"Failure",
MB_ICONINFORMATION);
exit(EXIT_FAILURE);
}