How can I get a hostname from an IPv4 address in C?
Solution 1
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.
Solution 2
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.
Solution 3
To get the host name from an address, you normally use (big surprise here)
gethostbyaddr()
.Yes, probably.
user884685
Updated on June 28, 2022Comments
-
user884685 almost 2 years
I need a simple function that outputs a
char* hostname
, given achar* IPAddress
. Any ideas or hints?Also, is easiest way to get the IP address from a hostname is
gethostbyname()
andinet_ntoa()
is that correct?-
Alexis Wilke over 7 yearsNote that the
inet_ntoa()
only converts in memory from asockaddr
structure to a string in numeric notation. No support for domain names.
-
-
user884685 about 12 yearsI'll take a look at it. Thanks.