我正在尝试编写一些客户端代码,以将UDP数据包发送到具有特定IP地址的另一台计算机。当IP地址设置为home时,它工作正常。我可以使用Wireshark查看发送的数据包。当我放入服务器的IP时,我没有看到任何数据包。经过进一步调查,我发现尝试绑定到套接字时遇到了10049错误。我不太明白为什么我无法绑定到网络上另一台计算机的IP。
string m_port = "2033"; // port that the plugin is talking to
string m_hostIP = "192.168.2.27"; // IP address that the plugin is talking to
// start Windows Sockets
if ((error = WSAStartup(version, &data)) != NO_ERROR)
{
logError("Error: WSAStartup failed with error: ", error);
return;
}
// check if version 2.2 of Winsock is supported
if (LOBYTE(data.wVersion) != 2 || HIBYTE(data.wVersion) != 2)
{
logError("Error: System could not support WinSock 2.2.", 0);
// clean up Winsock
if (WSACleanup() == SOCKET_ERROR)
{
logError("Error: Winsock cleanup error: ", WSAGetLastError());
}
return;
}
// create a datagram socket using IPv4 and UDP protocol
if ((m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET)
{
logError("Error: Socket creation failed with error: ", WSAGetLastError());
// clean up Winsock
if (WSACleanup() == SOCKET_ERROR)
{
logError("Error: Winsock cleanup error: ", WSAGetLastError());
}
return;
}
int iSetOption = 1;
if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&iSetOption, sizeof(iSetOption)) == SOCKET_ERROR)
{
logError("Error: Set Socket Options failed with error: ", WSAGetLastError());
// close the socket
if (closesocket(m_socket) == SOCKET_ERROR)
{
logError("Error: Unable to close socket: ", WSAGetLastError());
}
// clean up Winsock
if (WSACleanup() == SOCKET_ERROR)
{
logError("Error: Winsock cleanup error: ", WSAGetLastError());
}
m_socket = INVALID_SOCKET;
return;
}
struct sockaddr_in server_addr; // server address description struct
int server_addr_len = sizeof(server_addr); // size of server address struct
int bytesSent = 0;
memset((char *)&server_addr, 0, server_addr_len); // clear the address struct
server_addr.sin_family = AF_INET; // IPv4 address type
server_addr.sin_port = htons((unsigned short)stoul(m_port)); // port used by the simulator to send the data
server_addr.sin_addr.s_addr = inet_addr(m_hostIP.c_str()); // any server IP address will do
// bind the socket to the address struct
if (::bind(m_socket, (struct sockaddr *) &server_addr, server_addr_len) == SOCKET_ERROR)
{
logError("Error: unable to bind the socket: ", WSAGetLastError());
// close the socket
if (closesocket(m_socket) == SOCKET_ERROR)
{
logError("Error: Unable to close socket: ", WSAGetLastError());
}
// clean up Winsock
if (WSACleanup() == SOCKET_ERROR)
{
logError("Error: Winsock cleanup error: ", WSAGetLastError());
}
m_socket = INVALID_SOCKET;
return;
}
答案 0 :(得分:0)
您绑定套接字以选择从哪个本地端点(地址+端口)发送数据。
服务器可能具有多个将您连接到Internet的网卡,或者您可能具有多个网络-通过绑定,您可以选择从哪个网卡(或实际的网卡)中发送数据。
通常,PC仅具有一些可行的地址(本地主机和网络地址),但您也可以指定端口。端口可用于过滤不需要的数据包,这在您要创建多个套接字时很有用。
另一个操作称为connect
-选择向哪个远程端点发送数据。我不记得确切的细节如何在winsocket / udp上工作。可能没有必要,您只需发送数据,然后指定每次发送的位置即可。