<< Prev | Beej's Guide to Network Programming | Next >> |
Convert IP addresses from a dots-and-number string to a
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> // ALL THESE ARE DEPRECATED! Use inet_pton() or inet_ntop() instead!! char *inet_ntoa(struct in_addr in); int inet_aton(const char *cp, struct in_addr *inp); in_addr_t inet_addr(const char *cp);
These functions are deprecated because they don't handle IPv6! Use inet_ntop() or inet_pton() instead! They are included here because they can still be found in the wild.
All of these functions convert from a
The function inet_ntoa() converts a network address in a
The function inet_aton() is the opposite, converting
from a dots-and-numbers string into a
Finally, the function inet_addr() is an older function that does basically the same thing as inet_aton(). It's theoretically deprecated, but you'll see it a lot and the police won't come get you if you use it.
inet_aton() returns non-zero if the address is a valid one, and it returns zero if the address is invalid.
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
struct sockaddr_in antelope; char *some_addr; inet_aton("10.0.0.1", &antelope.sin_addr); // store IP in antelope some_addr = inet_ntoa(antelope.sin_addr); // return the IP printf("%s\n", some_addr); // prints "10.0.0.1" // and this call is the same as the inet_aton() call, above: antelope.sin_addr.s_addr = inet_addr("10.0.0.1");
inet_ntop(), inet_pton(), gethostbyname(), gethostbyaddr()
<< Prev | Beej's Guide to Network Programming | Next >> |