Tutorial :Get IP address of arriving data package



Question:

So I'm creating an input socket using

CFSocketCreateWithSocketSignature (NULL, &signature, kCFSocketDataCallBack, receiveData, &socket_context);

Within the receiveData function (that gets called properly) I'm trying to use the CFDataRef address parameter to find out the sender address of the this "package".

The IP address of the sender PC is at 192.168.1.2.

I'm using

char buffer[INET_ADDRSTRLEN]; NSLog([NSString stringWithFormat:@"incoming connection from: %s", inet_ntop(AF_INET, address, buffer, INET_ADDRSTRLEN)]);

However I always get the 192.6.105.48 out of the log. What gives? I'm really not big on networking in Cocoa/C so any help / explanation is very much appreciated.

Thanks in advance!


Solution:1

Here is a Category class of NSData that I've implemented for one of my projects. Using the toll-free bridge between CFDataRef and NSData you can use the following class.

@implementation NSData (Additions)    - (int)port  {      int port;      struct sockaddr *addr;        addr = (struct sockaddr *)[self bytes];      if(addr->sa_family == AF_INET)          // IPv4 family          port = ntohs(((struct sockaddr_in *)addr)->sin_port);      else if(addr->sa_family == AF_INET6)          // IPv6 family          port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port);      else          // The family is neither IPv4 nor IPv6. Can't handle.          port = 0;        return port;  }      - (NSString *)host  {      struct sockaddr *addr = (struct sockaddr *)[self bytes];      if(addr->sa_family == AF_INET) {          char *address =             inet_ntoa(((struct sockaddr_in *)addr)->sin_addr);          if (address)              return [NSString stringWithCString: address];      }      else if(addr->sa_family == AF_INET6) {          struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;          char straddr[INET6_ADDRSTRLEN];          inet_ntop(AF_INET6, &(addr6->sin6_addr), straddr,               sizeof(straddr));          return [NSString stringWithCString: straddr];      }      return nil;  }    @end  


Solution:2

It could be that the network-traffic is NAT/masqueraded on the way to the receiving end. The IP address you've given for the sender PC is in one of the RFC 1918 private/unrouted networks, whereas the IP address you're seeing is on a routed network-block.


Solution:3

Well, barring programming mistakes and assuming Mac platform, check output of ifconfig on both machines, check the routing with route get <IP> from both machines; and all the way down to tcpdump.

By the way, having BSD layer really pays off on Mac - if you don't know how to use a tool just man it, like man tcpdump.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »