简体   繁体   中英

How do I extract IP address and port number from NSData

- (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 is NSData, How do I extract IP address and port number from addrObj?

I think you don't need to use a NSData object to extract the address. I use the following code to extract the IP address and port from which I read:

- (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);
    ...
}

Sample output:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM