Segmentation error when searching for hostname and IP address

I have the following code snippet to get the host name and IP address,

#include <stdlib.h> #include <stdio.h> #include <netdb.h> /* This is the header file needed for gethostbyname() */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> int main(int argc, char *argv[]) { struct hostent *he; if (argc!=2){ printf("Usage: %s <hostname>\n",argv[0]); exit(-1); } if ((he=gethostbyname(argv[1]))==NULL){ printf("gethostbyname() error\n"); exit(-1); } printf("Hostname : %s\n",he->h_name); /* prints the hostname */ printf("IP Address: %s\n",inet_ntoa(*((struct in_addr *)he->h_addr))); /* prints IP address */ } 

But during compilation I get a warning:

 $cc host.c -o host host.c: In function 'main': host.c:24: warning: format '%s' expects type 'char *', but argument 2 has type 'int' 

Then, when the code is executed, a segmentation error occurs:

 ./host 192.168.1.4 Hostname : 192.168.1.4 Segmentation fault 

What is the error in the code?

+6
c
source share
5 answers

The printf format mismatch warning is an important warning. In this case, this is because the compiler thinks that the inet_ntoa function returns an int , but you indicated that you want to expect a string in the format.

The incorrect return type for inet_ntoa is the result of the old C rule, which says that if you try to use a function without a prior declaration, then the compiler must assume that the function returns int and accepts an unknown (but fixed) number of arguments. The mismatch between the supposed return type and the actual type of the returned function results in undefined behavior, which appears to fail in your case.

The solution is to include the correct header for inet_ntoa .

+6
source share

I had a similar code (if not the same one) and it compiled perfectly on a machine in our school lab, but when I compiled it on my machine at home, it had the same error (I did not edit the code). I read the manual page for inet and found that I did not have one header file, which is #include <arpa/inet.h> . After I added this header to my C program, it compiled and works fine.

+8
source share

Break this code:

 printf("IP Address: %s\n",inet_ntoa(*((struct in_addr *)he->h_addr))); 

In it:

 struct in_addr* address = (in_addr*) he->h_addr; char* ip_address = inet_ntoa(*address); printf("IP address: %s\n", ip_address); 

It also makes debugging and problem identification easier.

+1
source share

Actually, I just compiled this code on my FreeBSD machine at home, and it works.

0
source share

You can try resetting the he->h_addr value before trying to dereference it and pass it to inet_ntoa . If it was NULL , this will result in a seg error.

How to pass it through strace ?

0
source share

All Articles