cocoa - 将 NSData 转换为 NSString

标签 cocoa nsdata

我收到与服务器的成功连接,并且我正在回调函数中:

我正在尝试获取主机的名称并将其打印到我的控制台:

if(theType == kCFSocketConnectCallBack){
        NSLog(@"Connection is accepted");
        CFSocketNativeHandle nativeSocket = CFSocketGetNative(theSocket);
        uint8_t name[SOCK_MAXADDRLEN];
        socklen_t namelen = sizeof(name);
        NSData *peer = nil;
        if (getpeername(nativeSocket, (struct sockaddr *)name, &namelen) == 0) {
            peer = [NSData dataWithBytes:name length:namelen];
            NSString *string = [[NSString alloc] initWithData:peer encoding:NSUTF8StringEncoding];
            NSLog(@"IP adress of connected peer: %@", string);
        } 

当我在 Debug模式下运行应用程序时,我可以看到分配给 name 的 IP 地址值,因此成功获取了 name ,每个值都是 uint8_t 。 对等长度显示为 16; 我的问题是将其转换为 NSData 然后 NSString...

输出: 2010-01-31 13:57:58.671 连接对等点的 IP 地址: (null)

我的字符串输出为 NULL,

任何建议表示赞赏,谢谢......

最佳答案

getpeername() 不返回远程端的主机名;它返回地址:

$ man getpeername

...

DESCRIPTION
     The getpeername() function returns the address of the peer connected to
     the specified socket.

你想要 getnameinfo():

$ man getnameinfo

...

DESCRIPTION
     The getnameinfo() function is used to convert a sockaddr structure to a
     pair of host name and service strings.  It is a replacement for and pro-
     vides more flexibility than the gethostbyaddr(3) and getservbyport(3)
     functions and is the converse of the getaddrinfo(3) function.

或 gethostbyaddr():

$ man gethostbyaddr

...

DESCRIPTION
     The getaddrinfo(3) and getnameinfo(3) functions are preferred over the
     gethostbyname(), gethostbyname2(), and gethostbyaddr() functions.

     The gethostbyname(), gethostbyname2() and gethostbyaddr() functions each
     return a pointer to an object with the following structure describing an
     internet host referenced by name or by address, respectively.

关于cocoa - 将 NSData 转换为 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2172834/

相关文章:

objective-c - 是否可以使用 iOS 在运行时连接对象?

objective-c - NSNotification/绑定(bind)?

swift - NSData contentsOfUrl 在图像很大时返回 nil

iphone - 如何获取 NSData 对象中的第一个和第二个字节?

ios - 直接使用 SSZipArchive 压缩 NSData 不工作

cocoa - 根据表格列的 isEnabled 出价自定义 NSTextFieldCell

ios - GooglePlacePicker 不通过 cocoa pod 安装

cocoa - 属性(property)的返回地址

ios - 如何使用字符串数组将结构转换为 NSData,反之亦然 Swift

iphone - NSData writeToFile 适用于模拟器但不适用于设备