C inet_ntop:设备上没有剩余空间
嗨,我创建了一个函数,该函数接受接受的sockFD作为输入,并以表示形式将ip地址输出为字符串。函数似乎工作得很好,直到我开始使用inet_ntop的调用打包字符串,该调用返回空指针,从而给出错误。错误读作设备上没有剩余空间,我不理解,因为我有大量的ram和rom。总之,下面是我正在使用的函数C inet_ntop:设备上没有剩余空间,c,linux,sockets,C,Linux,Sockets,嗨,我创建了一个函数,该函数接受接受的sockFD作为输入,并以表示形式将ip地址输出为字符串。函数似乎工作得很好,直到我开始使用inet_ntop的调用打包字符串,该调用返回空指针,从而给出错误。错误读作设备上没有剩余空间,我不理解,因为我有大量的ram和rom。总之,下面是我正在使用的函数 void getTheirIp(int s, char *ipstr){ // int s is the incoming socketFD, ipstr points the the calling
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
缓冲区的可用长度。如手册页所述,从inet\u ntop获取ENOSPC意味着:
转换后的地址字符串将超过size给定的大小
将sizeof(ipstr)作为size参数,它是字符指针ipstr所占用的存储量。您需要将缓冲区的大小传递给它。首先,我将使用双指针:
void getTheirIp(int s, char **ipstr_pp)
下一步-这是错误的:ipstr是一个4字节指针:
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr)
我想你想要的是“INET_ADDRSTRLEN”
最后,我鼓励您打印出实际错误。或者至少剪切/粘贴完整的perror()文本(我认为应该包括错误#)。哦,我明白了,你指的是我分配了多少内存,而不是地址的实际大小。这就是你的意思吗?我认为sizeof()正在获得分配的内存量。谢谢JFTR:perror()通常不包括errno编号,但是包含的strerror(errno)也一样好。确切地说,POSIX说它应该包含用户指定的字符串、冒号以及strerror()将给出的相同消息。谢谢