2

I tried to find the IP address that my UDP socket is bound to (assuming I don't want to use another method to find the computer's IP address). How can this be done? The code below works for the PORT number, but always returns 0.0.0.0 for the address:

struct sockaddr_in sin;
int addrlen = sizeof(sin);
if(getsockname(clientSock, (struct sockaddr *)&sin, &addrlen) == 0 &&
    sin.sin_family == AF_INET &&
    addrlen == sizeof(sin)){
    printf("RETURNING ADDR: %s: len = %d\n", inet_ntoa(sin.sin_addr),
        strlen(inet_ntoa(sin.sin_addr)));
}

The socket was bound using the following code:

sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;//inet_addr("127.0.0.1");
local.sin_port = 0; //assign given port
result = bind(clientSock, (sockaddr*)&local, sizeof(local));

Thank you for any and all help. I appreciate your time!

Richard
  • 21
  • 1
  • 2

1 Answers1

2

0.0.0.0 is INADDR_ANY, meaning the socket is bound to all local addresses on the host, not just one address. You are asking for one address, but you are not bound to one address, so getsockname() cannot report a specific address.

If you want getsockname() to report a specific address, you have to bind() to that specific address. So use GetAdaptersAddresses to enumerate all interfaces on the local host and bind() a separate socket to each address, instead of binding INADDR_ANY on a single socket.

Otherwise, you can bind() a single socket to INADDR_ANY, and then use WSARecvMsg() (instead of recv(), recvfrom(), or WSARecvFrom()) to read the incoming packets. WSARecvMsg() can report details about each packet's arrival interface and destination address, if you enable the appropriate options with setsockopt().

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Steve-o
  • 12,678
  • 2
  • 41
  • 60
  • The socket will receive datagrams over multiple interfaces. It is, however, possible to determine which interface was traversed by any given incoming datagram. – Ben Voigt Sep 15 '14 at 06:38