Get the IP address of the incoming data packet

So, I create an input socket using

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

In the receiveData function (which is called correctly) I am trying to use a parameter CFDataRef address

to find out the sender address of this "packet".

The IP address of the sender PC is at 192.168.1.2.

I use

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

However, I always get 192.6.105.48 from the log. What gives? I'm really not big on the net at Cocoa / C so any help / explanation is greatly appreciated.

Thanks in advance!

0


a source to share


3 answers


Here is an NSData category class that I implemented for one of my projects. Using the 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

      

+8


a source


Possibly the network traffic is NAT / masqueraded en route to the receiving end. The IP address you provided for the sender PC is on one of the RFC 1918 private / non-propagated networks, whereas the IP address you see is on a routed network block.



+1


a source


Well, avoiding programming errors and assuming a Mac platform, check the output ifconfig

on both machines, check the routing route get <IP>

with both machines; and up to tcpdump

.

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

, for example man tcpdump

.

0


a source







All Articles