How to get IP address in qt / linux?

I am working on a server client project on Qt. The server runs on a machine with multiple network interfaces. The design is such that the client will automatically detect the server. those. the client will broadcast its IP address to the network, the server will receive this message and send back the IP address of the server. The problem is that when I try to get the IP address on the server, there are more than 1 IP address. How to get the IP address of the interface through which the server received the message?

+3
source share
1 answer

This may be the solution for you.

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 udp-socket (C / C ++)


To get the incoming peer IP, you can use the following solution in 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);

0

All Articles