我正在研究Qt上的服务器客户端项目。服务器在具有多个网络接口的计算机上运行。设计是这样的,客户端将自动发现服务器。即客户端将其IP广播到网络,服务器获取该消息并发回服务器的IP。现在的问题是,当我尝试在服务器中获取IP时,有超过1个IP。如何获取服务器收到消息的接口的IP?
答案 0 :(得分:0)
这可能是您的解决方案
IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr )
{
foreach( adapter in EnumAllNetworkAdapters() )
{
adapterSubnet = adapter.subnetmask & adapter.ipaddress;
senderSubnet = adapter.subnetmask & senderAddr;
if( adapterSubnet == senderSubnet )
{
return adapter.ipaddress;
}
}
}
How to get your own (local) IP-Address from an udp-socket (C/C++)
要获取传入的对等IP地址,您可以在C
socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET6_ADDRSTRLEN];
int port;
len = sizeof addr;
getpeername(s, (struct sockaddr*)&addr, &len);
// deal with both IPv4 and IPv6:
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}
printf("Peer IP address: %s\n", ipstr);