Get peer IP address and port on OSX in objective-c from NSStream, CFStream or Socket

痴心易碎 提交于 2019-12-04 17:20:13

Okay I figured it out by now. This is what I did:

- (void)getPublicClientAddress {
    // Get public IP from stream

    // Get hands on appropriate data structures via the socket number
    CFSocketNativeHandle nativeSocketHandle = _socketnumber;
    uint8_t name[SOCK_MAXADDRLEN];
    socklen_t namelen = sizeof(name);
    NSData *peer = nil;
    if (0 == getpeername(nativeSocketHandle, (struct sockaddr *)name, &namelen)) {
        peer = [NSData dataWithBytes:name length:namelen];
    }

    if (_ipv6){
        // If ipv6 is used
        struct sockaddr_in6 *socketaddress = (struct sockaddr_in6*)name;

        // convert ip to string
        char *ipstr = malloc(INET6_ADDRSTRLEN);
        struct in6_addr *ipv6addr = &socketaddress->sin6_addr;
        inet_ntop(AF_INET6, ipv6addr, ipstr, sizeof(ipstr));

        // convert port to int
        int portnumber = socketaddress->sin6_port;

        // Save in properties
        _publicIP   = [NSString stringWithFormat:@"%s", ipstr];
        _publicPort = [NSString stringWithFormat:@"%d", portnumber];
    } else {
        // If ipv4 is used
        struct sockaddr_in *socketaddress = (struct sockaddr_in*)name;

        // convert ip to string
        char *ipstr = malloc(INET_ADDRSTRLEN);
        struct in_addr *ipv4addr = &socketaddress->sin_addr;
        ipstr = inet_ntoa(*ipv4addr);
        //inet_ntop(AF_INET, ipv4addr, ipstr, sizeof(ipstr));

        // convert port to int
        int portnumber = socketaddress->sin_port;

        // Save in properties
        _publicIP   = [NSString stringWithFormat:@"%s", ipstr];
        _publicPort = [NSString stringWithFormat:@"%d", portnumber];
    }
}

Afterwards you will have the public IP in the property _publicIP and the public port in the property _publicPort. All information is gathered from a connection on the server side.

I hope this post will help someone =)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!