我收到与服务器的成功连接,并且我正在回调函数中:
我正在尝试获取主机的名称并将其打印到我的控制台:
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/