简体   繁体   中英

sin_port in sockaddr_in

Which port should I use if I need to get the hostname of an IP ? From where does getnameinfo() get the hostname ?

struct sockaddr_in sa;
sa.sin_family    = AF_INET;
sa.sin_port    = htons(?); // which port ?
inet_pton(AF_INET, "x.x.x.x", &(sa.sin_addr));

char host[NI_MAXHOST];
getnameinfo((struct sockaddr *)&sa, sizeof(sa), host, NI_MAXHOST, NULL, 0, NI_NAMEREQD);

puts(host);

If you don't use serv and servlen arguments, port number is irrelevant. Otherwise it's used to look up the service by the port number, something like "ssh" for port 22, "smtp" for port 25, etc. (see /etc/services for more).

getnameinfo() can get the hostname from a number of places (with nsswitch.conf , miscellaneous libnss modules can be enabled for different kinds of name resolution). On a typical desktop linux distro, I'd expect it to look at /etc/hosts first, then query DNS servers according to /etc/resolv.conf .

From http://www.kernel.org/doc/man-pages/online/pages/man3/getnameinfo.3.html :

The sa argument is a pointer to a generic socket address structure (of type sockaddr_in or sockaddr_in6) of size salen that holds the input IP address and port number. The arguments host and serv are pointers to caller-allocated buffers (of size hostlen and servlen respectively) into which getnameinfo() places null-terminated strings containing the host and service names respectively.

The caller can specify that no hostname (or no service name) is required by providing a NULL host (or serv) argument or a zero hostlen (or servlen) argument. However, at least one of hostname or service name must be requested.

So, if you're only interested in the hostname, don't provide a buffer for the service name.

I'll defer to others on the topic of where this comes from, but the code is in glibc if you're curious.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM