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?
The inet_ntoa function takes an Internet address structure specified by the in parameter and returns a NULL-terminated ASCII string that represents the address in "." (dot) notation as in "192.168. 16.0", an example of an IPv4 address in dotted-decimal notation.
The inet_ntoa function need not be reentrant, and consequently is not required to be thread safe. Implementations of inet_ntoa typically write the timestamp into static buffer.
inet_ntoa() returns the dots-and-numbers string in a static buffer that is overwritten with each call to the function. inet_addr() returns the address as an in_addr_t, or -1 if there's an error. (That is the same result as if you tried to convert the string "255.255. 255.255", which is a valid IP address.
The inet_aton() function converts the Internet host address cp from the IPv4 numbers-and-dots notation into binary form in network byte order and stores it in the structure that inp points to. The address that is supplied in cp can be in one of the following forms: a.b.c.d.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With