Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

segmentation fault for inet_ntoa

Tags:

c

    #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?

like image 403
user138126 Avatar asked Mar 26 '13 11:03

user138126


3 Answers

inet_ntoa does not demand a pointer, but value

 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.

inet_ntoa will return NULL if there is an error, so trying to printf a NULL will cuase a segmentation fault...

Look here for information and here for the man-page.

like image 92
bash.d Avatar answered Nov 03 '22 03:11

bash.d


inet_ntoa is defined in the header <arpa/inet.h>,
need to #include, otherwise, there will be errors

like image 27
user138126 Avatar answered Nov 03 '22 03:11

user138126


If you don't want to see the warning, just cast the return value of 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.

like image 30
Davide Berra Avatar answered Nov 03 '22 01:11

Davide Berra