title: Get peer IP address and port on OSX in objective-c from NSStream, CFStream or Socket
body: <p>I have written a server that listens on a specific port for incoming tcp connections. To manage the network connectivity I am using Streams (CFStream/NSStream). When a connection is esthablished I save all the information about this very connection in another instance of a dedicated class which is also set as the delegate for the streams.</p>
  
  <p>Now I want to get the public IP of the device that sends me a message through the already esthablished streams, in other words, I would like to store the IP of the stream's peer. I tried many things, but unfortunately I only get null-values.</p>
  
  <p>Is there a possibility to get the peer's address (ip and port) from an existing stream of the described form?</p>
  
  <p>Here is some code I have tried:</p>
  
  <pre><code>CFDataRef peerAddress = CFSocketCopyPeerAddress(_sockRef);
  // _sockRef is saved when connection is established in listening callback and is not null
  </code></pre>
  
  <p>I also tried to get the information direct in the listening callback method:</p>
  
  <pre><code>NSData *peer = nil;
  
  CFSocketNativeHandle nativeSocketHandle = *(CFSocketNativeHandle *)data;
  
  struct sockaddr *addressinfo = NULL;
  
  uint8_t name[SOCK_MAXADDRLEN];
  
  socklen_t namelen = sizeof(addressinfo);
  int result = getpeername(nativeSocketHandle, addressinfo, &amp;namelen);
  
  if (result == 0) {
  
        peer = [NSData dataWithBytes:name length:namelen];
  
   }
  
  struct sockaddr_in *s = (struct sockaddr_in*)name;
  
  char *ipstr = malloc(INET_ADDRSTRLEN);
  
  ipstr = inet_ntoa(s-&gt;sin_addr); // is 0.0.0.0 :-(
  </code></pre>
  
  <p>And I tried another method:</p>
  
  <pre><code>_publicIP = CFWriteStreamCopyProperty((__bridge CFWriteStreamRef)(_writeStream), kCFStreamPropertySocketRemoteHostName);
  </code></pre>
  
  <p>Why do I always get null-values? Can anyone help me?</p>
  
  <p>Thank you in advance!</p>