3

I used this as the address to create a new server(socket(), bind(), listen()):

struct sockaddr_in newServer;
memset(&newServer, 0, sizeof(newServer));
newServer.sin_family = AF_INET;
newServer.sin_addr.s_addr = htonl(INADDR_ANY);
newServer.sin_port = htons(UNUSED_PORT);

The macro UNUSED_PORT is defined as 0.

I expect to get a server listening on any interface and on an unused port.

I tried to use getsockname() to get my local IP address and port, but I got some strange outputs. The output code as below:

struct sockaddr_in localAddress;
socklen_t addressLength;
getsockname(newServerfd, (struct sockaddr*)&localAddress,   \
                &addressLength);
printf("local address: %s\n", inet_ntoa( localAddress.sin_addr));
printf("local port: %d\n", (int) ntohs(localAddress.sin_port));

For example, I got 0.255.255.255:0, 0.0.0.0:0, 255.127.0.0:36237, etc. and my system is Mac OS X 10.7.3.

--update--

After using socklen_t addressLength = sizeof(localAddress); (thanks to @cnicutar and @Jonathan Leffler), I always get 0.0.0.0 for local IP; is that all right?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
can.
  • 2,098
  • 8
  • 29
  • 42

1 Answers1

6

You need to initialize addressLength before calling getsockname:

socklen_t addressLength = sizeof(localAddress);
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • i always get 0.0.0.0 for local ip this time, is that normal? – can. Apr 17 '12 at 03:20
  • 1
    If you've bound to 0.0.0.0, then yes. – Sebastian Apr 17 '12 at 04:09
  • @macs then how can i get the **real** ip? – can. Apr 17 '12 at 06:43
  • @can. Take a look at [this](http://stackoverflow.com/questions/212528/linux-c-get-the-ip-address-of-local-computer) SO question if you want to have the IP-address(es) of your machine. What you've done so far is that you've bound a socket and this socket listens on 0.0.0.0 which means everyone can connect. – Sebastian Apr 17 '12 at 06:45
  • @macs thanks.i've seen that question before. and i finally get a thorough understanding of _local address_. 0.0.0.0 means every _interface_ of server accepts incoming connections, i can only get the exact local ip from a socket that transfers data, not the listening socket, in my example. – can. Apr 17 '12 at 09:26