Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

something about inet_ntoa()

Tags:

c

linux

unix

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?

like image 873
venus.w Avatar asked Jun 15 '12 11:06

venus.w


People also ask

Why Inet_ntoa () function is used?

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.

Is Inet_ntoa thread safe?

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.

How inet_ ntoa works?

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.

What is Inet_aton in C?

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.


1 Answers

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.

like image 151
Piotr Praszmo Avatar answered Sep 30 '22 06:09

Piotr Praszmo