各位程序员大家好!我正在用 C++ 编写一个程序,该程序应该允许使用 Windows 套接字通过 LAN 在两台计算机之间进行实时数据传输。由于数据应该尽可能快地传输,我使用 UDP(这是一个游戏,因此只有最新的数据是相关的)。现在,因为我在单台机器上测试过它,所以我使用以下代码将服务器 IP 分配给客户端
SOCKADDR_IN server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
server_address.sin_addr.S_un.S_un_b.s_b1 = 127;
server_address.sin_addr.S_un.S_un_b.s_b2 = 0;
server_address.sin_addr.S_un.S_un_b.s_b3 = 0;
server_address.sin_addr.S_un.S_un_b.s_b4 = 1;
现在,我需要它在 LAN 中运行,其中服务器和客户端的确切地址可能是未知的。在这种情况下如何连接?如果我广播到 255.255.255.255 就够了吗?或者,也许还有另一种方式来握手 2 台计算机?
好的,我完成了我的项目,所以我将借此机会展示我用于查找服务器的代码。如建议的那样,它基于客户端广播并发回数据报,将服务器的 IP 提供给客户端,稍后用于提供定向通信。
服务器:
bool handshakeS()
{
SOCKET sockhs;
sockhs = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
char broadcast = '1';
if (setsockopt(sockhs, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) < 0)
{
closesocket(sockhs);
return false;
}
struct sockaddr_in Recv_addr;
struct sockaddr_in Sender_addr;
int len = sizeof(struct sockaddr_in);
char recvbuff[1];
int recvbufflen = 1;
char sendMSG[] = "";
Recv_addr.sin_family = AF_INET;
Recv_addr.sin_port = htons(PORTHS);
Recv_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockhs, (sockaddr*)&Recv_addr, sizeof(Recv_addr)) < 0)
{
closesocket(sockhs);
return false;
}
recvfrom(sockhs, recvbuff, recvbufflen, 0, (sockaddr*)&Sender_addr, &len);
if (sendto(sockhs, sendMSG, strlen(sendMSG) + 1, 0, (sockaddr*)&Sender_addr, sizeof(Sender_addr)) < 0)
{
closesocket(sockhs);
return false;
}
return true;
closesocket(sockhs);
}
客户:
bool handshakeC(int& ip1temp, int& ip2temp, int& ip3temp, int& ip4temp)
{
SOCKET sockhs;
sockhs = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
char broadcast = '1';
if (setsockopt(sockhs, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) < 0)
{
closesocket(sockhs);
return false;
}
struct sockaddr_in Recv_addr;
struct sockaddr_in Sender_addr;
int len = sizeof(struct sockaddr_in);
char sendMSG[] = ""; //may be used for authorization
char recvbuff[1] = "";
int recvbufflen = 1;
Recv_addr.sin_family = AF_INET;
Recv_addr.sin_port = htons(PORTHS);
Recv_addr.sin_addr.s_addr = INADDR_BROADCAST;
sendto(sockhs, sendMSG, strlen(sendMSG) + 1, 0, (sockaddr*)&Recv_addr, sizeof(Recv_addr));
recvfrom(sockhs, recvbuff, recvbufflen, 0, (sockaddr*)&Recv_addr, &len);
ip1temp = Recv_addr.sin_addr.S_un.S_un_b.s_b1;
ip2temp = Recv_addr.sin_addr.S_un.S_un_b.s_b2;
ip3temp = Recv_addr.sin_addr.S_un.S_un_b.s_b3;
ip4temp = Recv_addr.sin_addr.S_un.S_un_b.s_b4;
closesocket(sockhs);
return true;
}
我是一名优秀的程序员,十分优秀!