Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a hostname from an IPv4 address in C?

I need a simple function that outputs a char* hostname, given a char* IPAddress. Any ideas or hints?

Also, is easiest way to get the IP address from a hostname is gethostbyname() and inet_ntoa() is that correct?

like image 792
user884685 Avatar asked Dec 21 '25 11:12

user884685


2 Answers

Use gethostbyaddr() or getnameinfo() to convert an IP into a hostname.

Use gethostbyname() or getaddrinfo() to convert a hostname into an IP.

gethostby...() only support IPv4. get...info() support multiple protocols including both IPv4 and IPv6, and are the preferred functions for new development.

like image 54
Remy Lebeau Avatar answered Dec 24 '25 03:12

Remy Lebeau


All the information you need on this is in the excellent Beej's Guide to Network Programming. The page relevant to your question is here.

If after reading that, you are still having problems, post here with a question about a specific issue.

like image 33
Dave Avatar answered Dec 24 '25 01:12

Dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!