user138126
user138126

Reputation: 1003

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?

Upvotes: 10

Views: 10091

Answers (3)

user138126
user138126

Reputation: 1003

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

Upvotes: 22

Davide Berra
Davide Berra

Reputation: 6568

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.

Upvotes: 1

bash.d
bash.d

Reputation: 13207

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.

Upvotes: 2

Related Questions