Linux – something about inet_ntoa()

clinuxunix

I write a server using the function char* inet_ntoa(struct in_addr in), When I included the header
<sys/socket.h> and <netinet/in.h> ,an executable binary can be generated with compiler warnings, but a segment fault happens, when the program handle the return string from inet_ntoa. But when I added the header <arpa/inet.h>, everything seems ok.

What's the matter?

Best Answer

arpa/inet.h contains the declaration of char* inet_ntoa(struct in_addr in). If you don't include this header your compiler will use implicit declaration int inet_ntoa(). Wrong declaration can easily lead to segfault, especially if you are on system where sizeof(int)!=sizeof(void*).

If you are using gcc you can add -Wall flag. gcc will warn you about using functions without explicit declaration.

Related Topic