c - inet_ntop : No space left on device

标签 c linux sockets

您好,我创建了一个函数,该函数将接受的 sockFD 作为输入,并将表示形式的 ip 地址输出为字符串。该函数似乎工作正常,直到我开始使用 inet_ntop 的调用来打包字符串,该调用返回一个空指针,从而给了我错误。错误显示为 No space left on device 我不明白,因为我有足够的 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);

任何帮助都会很棒。谢谢!

最佳答案

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

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

关于c - inet_ntop : No space left on device,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9235798/

相关文章:

比较 C 中数组的内容

C 编程 - 用于处理多维数组的函数中的指针

c - 使用 if 语句的循环在 C 中无法正常工作

c - 目标在 Makefile 中的作用是什么?

c++ - 如何将信号量与共享内存结合使用

linux - TCP 重传计时器覆盖/杀死 TCP 保活计时器,延迟断开连接发现

java - 通过发送多个数据包通过线性回归计算带宽

c - "EXC_BAD_ACCESS: Unable to restore previously selected frame"错误,数组大小?

c++ - 在 Linux 中创建的包含 make 文件的 Visual Studio 2015 中编译 C++ 项目

C-套接字 : Programming a Client/Server-Application to send a file