如何从NSData中提取IP地址和端口号

时间:2011-03-30 23:13:10

标签: objective-c

- (void)readData{
    int                     err;
    int                     sock;
    struct sockaddr_storage addr;
    socklen_t               addrLen;
    uint8_t                 buffer[65536];
    ssize_t                 bytesRead;

    sock = CFSocketGetNative(self->_cfSocket);

    addrLen = sizeof(addr);
    bytesRead = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *) &addr, &addrLen);
    if (bytesRead < 0) {
        err = errno;
    } else if (bytesRead == 0) {
        err = EPIPE;
    } else {
        NSData *    dataObj;
        NSData *    addrObj;

        err = 0;

        dataObj = [NSData dataWithBytes:buffer length:bytesRead];
        addrObj = [NSData dataWithBytes:&addr  length:addrLen  ];

        // Tell the delegate about the data.
        NSLog(@"receive data");

        if ( (self.delegate != nil) && [self.delegate respondsToSelector:@selector(socket:didReceiveData:fromAddress:)] ) {
            [self.delegate socket:self didReceiveData:dataObj fromAddress:addrObj];
        }
    }

    if (err != 0) {
        NSLog(@"Did Receive Error");
    }
}

addrObj是NSData,如何从addrObj中提取IP地址和端口号?

1 个答案:

答案 0 :(得分:1)

我认为您不需要使用NSData对象来提取地址。我使用以下代码来提取我读过的IP地址和端口:

- (void)readData
{
    int                      sock = CFSocketGetNative(self.cfSocket);
    struct sockaddr_storage  address;
    socklen_t                len = sizeof(address);
    uint8_t                  buffer[65536];
    ssize_t                  bytesRead = recvfrom(sock, buffer, sizeof(buffer), 0, 
                                        (struct sockaddr *) &address, &len);
    int                      error = (bytesRead < 0) ? errno : 0;

    NSLog(@"%zi bytes read from %s:%d...", bytesRead, 
          inet_ntoa(((struct sockaddr_in*)&address)->sin_addr), 
          ((struct sockaddr_in*)&address)->sin_port);
    ...
}

示例输出:

2011-05-04 10:41:57.051,-[myClass readData],5 bytes read from 10.112.15.81:37259...
2011-05-04 10:41:57.052,-[myClass readData] read:
"Hello"