2012-02-10 83 views
2

嗨我创建了一个函数,它接受一个可接受的sockFD作为输入并将表示形式的IP地址输出到一个字符串。该函数似乎工作正常,直到我打开包装字符串与inet_ntop返回一个空指针,从而给我我的错误的调用。该错误读取为设备上没有空间,我不明白,因为我有大量的内存和ROM。无论如何波纹管是我正在使用的功能。inet_ntop:设备上没有剩余空间

void getTheirIp(int s, char *ipstr){ // int s is the incoming socketFD, ipstr points the the calling 
        // functions pointer. 
    socklen_t len; 
    struct sockaddr_storage addr; 
    len = sizeof(addr);   //I want to store my address in addr which is sockaddr_storage type 
    int stat; 
    stat = getpeername(s, (struct sockaddr*)&addr, &len); // This stores addrinfo in addr 
printf("getTheirIP:the value of getpeername %d\n",stat); 
    // deal with both IPv4 and IPv6: 
    if ((stat=addr.ss_family) == AF_INET) { // I get the size of the sock first 
     printf("getTheirIP:the value of addr.ss_family is %d\n",stat); 
     ipstr = malloc(INET_ADDRSTRLEN); // I allocate memory to store the string 
     struct sockaddr_in *s = (struct sockaddr_in *)&addr; // I then create the struct sockaddr_in which 
           // is large enough to hold my address 
     if(NULL == inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr))){ // I then use inet_ntop to 
     printf("getTheirIP:the value of inet_ntop is null\n");// retrieve the ip address and store 
     perror("The problem was");    // at location ipstr 
     } 

    } else { // AF_INET6 this is the same as the above except it deals with IPv6 length 
     ipstr = malloc(INET6_ADDRSTRLEN); 
     struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr; 
     inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof(ipstr)); 
    } 
    printf("%s",ipstr); 
} 

我忽略了程序的其余部分,因为它太大而不适合我只想着重于修复这部分。然而,下面我将向你展示我的main()的一部分,它调用这个函数。

newSock = accept(listenSock,(struct sockaddr *)&their_addr,&addr_size); 
    char *someString; 
    getTheirIp(newSock,someString); 

任何帮助将是伟大的。谢谢!

回答

7
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr)) 

sizeof是错误的,因为ipstr是一个指针(它会产生指针的大小,像48东西)。您需要传递ipstr缓冲区的可用长度。

+0

哦,我明白了,你的意思是我分配了多少内存,而不是地址的实际大小。你是这个意思吗?我认为sizeof()获得了分配的内存量。谢谢!!! – 2012-02-10 22:44:48

+1

老兄你完全统治,它的工作......谢谢再次感谢! – 2012-02-10 22:47:07

4

如在手册页所解释的,从inet_ntop得到ENOSPC指:

转换后的地址串将超过由给定大小的大小。

你给的sizeof(ipstr)作为大小参数,它是存储在字符指针ipstr需要的量。您需要将它传递给缓冲区的大小。

1

对于初学者来说,我会使用一个双指针来代替:

void getTheirIp(int s, char **ipstr_pp) 

下一页 - 这是错误的:ipstr是一个4字节的指针:

inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr) 

我想你想“ INET_ADDRSTRLEN“。

最后,我鼓励你打印出实际的错误#。或者至少剪切/粘贴完整的perror()文本(我相信它应该包含错误#)。

+0

JFTR:perror()通常不会包含errno号码,但包含的strerror(errno)也一样好。确切地说,POSIX说它应该包含用户指定的字符串,冒号,然后strerror()会给出相同的消息。 – fnl 2012-02-10 23:05:32

+0

双指针回答我会有的问题。谢谢。 – 2012-02-10 23:55:35

相关问题