inet_ntop:设备上没有剩余空间

3

你好,我创建了一个函数,它以接受的sockFD作为输入,并将IP地址以演示形式输出到字符串。该函数似乎正常工作,直到我使用inet_ntop调用打包字符串,返回空指针并给出错误。错误显示为设备上没有剩余空间,这一点我不理解,因为我有足够的RAM和ROM。无论如何,以下是我正在使用的函数。

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

任何帮助都将是极好的。谢谢!
3个回答

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

由于ipstr是指针,因此sizeof是错误的(它将产生指针的大小,类似于48)。您需要传递ipstr缓冲区的可用长度。


哦,我明白了,你是指我已分配的内存量,而不是地址的实际大小。你是这个意思吗?我原以为 sizeof() 是用来获取已分配内存量的。谢谢!!! - Dr.Knowitall

4

如manpage中所解释的,从inet_ntop获取ENOSPC意味着:

转换后的地址字符串将超过size指定的大小。

您将sizeof(ipstr)作为大小参数,这是char指针ipstr占用的存储量。您需要传递缓冲区的大小。


1

首先,我会使用双指针:

void getTheirIp(int s, char **ipstr_pp)

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

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

我认为你想要使用"INET_ADDRSTRLEN"。

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


JFTR:perror()通常不会包含errno错误编号,但是包含的strerror(errno)同样有效。准确来说,POSIX规定它应该包含用户指定的字符串,一个冒号,然后是与strerror()相同的错误信息。 - fnl
双指针回答了我本来会有的一个问题。谢谢。 - Dr.Knowitall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接