简体   繁体   English

inet_ntoa的分段错误

[英]segmentation fault for inet_ntoa

    #include <stdio.h> 
    #include <string.h> /* for strncpy */ 
    #include <sys/types.h> 
    #include <sys/socket.h> 
    #include <sys/ioctl.h> 
    #include <netinet/in.h> 
    #include <net/if.h> 

    int 
    main() 
    { 
     int fd;  
     struct ifreq ifr; 

     fd = socket(AF_INET, SOCK_DGRAM, 0);  

     /* I want to get an IPv4 IP address */ 
     ifr.ifr_addr.sa_family = AF_INET; 

     /* I want IP address attached to "eth0" */ 
     strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1); 

     ioctl(fd, SIOCGIFADDR, &ifr); 

     close(fd); 

     /* display result */ 
     char* ipaddr; 
     ipaddr = inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr); 
     printf("%s\n", ipaddr); 

     return 0; 
    } 

for this line: 对于这一行:

     ipaddr = inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr);         

I get 我明白了

iptry.c: In function ‘main’:
iptry.c:31:9: warning: assignment makes pointer from integer without a cast [enabled by default]

and for 并为

     printf("%s\n", ipaddr);

I get segmentation fault. 我得到分段错误。

What is wrong with this? 这有什么问题?

inet_ntoa is defined in the header <arpa/inet.h> , inet_ntoa在头文件<arpa/inet.h>
need to #include , otherwise, there will be errors 需要#include ,否则会有错误

inet_ntoa does not demand a pointer, but value inet_ntoa不要求指针,而是值

 char* ipaddr; 
 ipaddr = inet_ntoa(((struct sockaddr_in)(ifr.ifr_addr))->sin_addr); 

If sin_addr is a pointer, you'll need to dereference it. 如果sin_addr是一个指针,你需要取消引用它。

inet_ntoa will return NULL if there is an error, so trying to printf a NULL will cuase a segmentation fault... 如果有错误, inet_ntoa将返回NULL ,因此尝试printf为NULL将导致分段错误...

Look here for information and here for the man-page. 在这里查看信息, 这里是man-page。

If you don't want to see the warning, just cast the return value of inet_ntoa 如果您不想看到警告,只需转换inet_ntoa的返回值

ipaddr = (char *) inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr);

The segmentation fault is probably because some of the previous function returns an error (null value) and you didn't check it 分段错误可能是因为某些先前的函数返回错误(空值)而您没有检查它

The same code worked in my Linux Box. 相同的代码在我的Linux Box中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM