title: How to get local IP address and port in Unix socket programming?
body: <p>I used this as the address to create a new server(<code>socket()</code>, <code>bind()</code>, <code>listen()</code>):</p>
  
  <pre><code>struct sockaddr_in newServer;
  memset(&amp;newServer, 0, sizeof(newServer));
  newServer.sin_family = AF_INET;
  newServer.sin_addr.s_addr = htonl(INADDR_ANY);
  newServer.sin_port = htons(UNUSED_PORT);
  </code></pre>
  
  <p>The macro UNUSED_PORT is defined as 0.</p>
  
  <p>I expect to get a server listening on any interface and on an unused port.</p>
  
  <p>I tried to use <code>getsockname()</code> to get my local IP address and port, but I got some strange outputs. The output code as below:</p>
  
  <pre><code>struct sockaddr_in localAddress;
  socklen_t addressLength;
  getsockname(newServerfd, (struct sockaddr*)&amp;localAddress,   \
                  &amp;addressLength);
  printf("local address: %s\n", inet_ntoa( localAddress.sin_addr));
  printf("local port: %d\n", (int) ntohs(localAddress.sin_port));
  </code></pre>
  
  <p>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.</p>
  
  <p>--update--</p>
  
  <p>After using <code>socklen_t addressLength = sizeof(localAddress);</code> (thanks to @cnicutar and @Jonathan Leffler), I always get 0.0.0.0 for local IP; is that all right?</p>