1

I am receiving a successful connection to the server and i am in my callback function:

I am trying to get the name of the host and print that to my console:

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

When i run the application in the debug mode i can see the IP address value assigned to name , so it's successful in getting the name , each value is uint8_t.. The peer length is showing me 16; My problem converting it to NSData then NSString...

output: 2010-01-31 13:57:58.671 IP adress of connected peer: (null)

My string is being output as NULL,

Any advise is appreciated, thanks....

4

3 回答 3

2

sockaddr是一个结构,而不仅仅是字符数组的 typedef。您需要将getpeername地址传递给实际的sockaddr结构,然后从该sa_data结构的字段构建字符串 - 并且假设它sa_data实际上是您的地址类型的字符串,文档并不建议您实际上可以依赖它。正如另一个答案所说,如果您的目标是打印出字符串表示,这不是您想要的调用。

(此外,您根本不需要 NSData 从字符数组到 NSString;您可以使用-[NSString initWithBytes:length:encoding:]

于 2010-01-31T21:27:50.183 回答
2

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

$ 人 getpeername

...

描述
     getpeername() 函数返回连接的对等体的地址
     指定的套接字。

你想要getnameinfo():

$ 人获取名称信息

...

描述
     getnameinfo() 函数用于将 sockaddr 结构转换为
     一对主机名和服务字符串。它是一个替代品和亲
     比 gethostbyaddr(3) 和 getservbyport(3) 更灵活
     函数,是 getaddrinfo(3) 函数的逆函数。

或 gethostbyaddr():

$ man gethostbyaddr

...

描述
     getaddrinfo(3) 和 getnameinfo(3) 函数优先于
     gethostbyname()、gethostbyname2() 和 gethostbyaddr() 函数。

     gethostbyname()、gethostbyname2() 和 gethostbyaddr() 函数各
     返回指向具有以下结构的对象的指针,该结构描述
     分别按名称或地址引用的 Internet 主机。
于 2010-01-31T19:10:41.900 回答
1

First, check to make sure that peer contains an instance of NSData that is non-zero in length.

If it does, then the most likely problem is that the data is not properly of the specified encoding causing NSString to fail the encoding and return a nil string. If it is an encoding issue, there is API on NSString for doing lossy encodings. Even if lossy isn't acceptable in your final solution, going that route can be quite helpful to figuring out what is going wrong.

That assumes by NULL you really mean nil. It would be helpful to paste the exact output of the log line.

于 2010-01-31T18:50:55.487 回答