How to get your own (local) IP-Address from an udp-socket (C/C++)

The solution provided by timbo assumes that the address ranges are unique and not overlapping. While this is usually the case, it isn't a generic solution.

There is an excellent implementation of a function that does exactly what you're after provided in the Steven's book "Unix network programming" (section 20.2) This is a function based on recvmsg(), rather than recvfrom(). If your socket has the IP_RECVIF option enabled then recvmsg() will return the index of the interface on which the packet was received. This can then be used to look up the destination address.

The source code is available here. The function in question is 'recvfrom_flags()'


G'day,

I assume that you've done your bind using INADDR_ANY to specify the address.

If this is the case, then the semantics of INADDR_ANY is such that a UDP socket is created on the port specified on all of your interfaces. The socket is going to get all packets sent to all interfaces on the port specified.

When sending using this socket, the lowest numbered interface is used. The outgoing sender's address field is set to the IP address of that first outgoing interface used.

First outgoing interface is defined as the sequence when you do an ifconfig -a. It will probably be eth0.

HTH.

cheers, Rob


You could enumerate all the network adapters, get their IP addresses and compare the part covered by the subnet mask with the sender's address.

Like:

IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr )
{
    foreach( adapter in EnumAllNetworkAdapters() )
    {
        adapterSubnet = adapter.subnetmask & adapter.ipaddress;
        senderSubnet = adapter.subnetmask & senderAddr;
        if( adapterSubnet == senderSubnet )
        {
            return adapter.ipaddress;
        }
    }
}

Tags:

C++

Sockets

Udp