Christopher Christopher - 1 year ago 110
C++ Question

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

  1. You have multiple network adapters.

  2. Bind a UDP socket to an local port, without specifying an address.

  3. Receive packets on one of the adapters.

How do you get the local ip address of the adapter which received the packet?

The question is, "What is the ip address from the receiver adapter?" not the address from the sender which we get in the

receive_from( ..., &senderAddr, ... );


Answer Source

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.


IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr )
    foreach( adapter in EnumAllNetworkAdapters() )
        adapterSubnet = adapter.subnetmask & adapter.ipaddress;
        senderSubnet = adapter.subnetmask & senderAddr;
        if( adapterSubnet == senderSubnet )
            return adapter.ipaddress;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download