Shammer's Philosophy

My private adversaria

man getnameinfo

例によって、man getnameinfo からの引用。man コマンドはすごいな。まず、宣言部。

     int
     getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host,
         socklen_t hostlen, char *serv, socklen_t servlen, int flags);

次にDescription。

DESCRIPTION
     The getnameinfo() function is used to convert a sockaddr structure to a
     pair of host name and service strings.  It is a replacement for and pro-
     vides more flexibility than the gethostbyaddr(3) and getservbyport(3)
     functions and is the converse of the getaddrinfo(3) function.
...
     The sockaddr structure sa should point to either a sockaddr_in,
     sockaddr_in6 or sockaddr_dl structure (for IPv4, IPv6 or link-layer
     respectively) that is salen bytes long.

     The host and service names associated with sa are stored in host and serv
     which have length parameters hostlen and servlen.  The maximum value for
     hostlen is NI_MAXHOST and the maximum value for servlen is NI_MAXSERV, as
     defined by <netdb.h>.  If a length parameter is zero, no string will be
     stored.  Otherwise, enough space must be provided to store the host name
     or service string plus a byte for the NUL terminator.

     The flags argument is formed by OR'ing the following values:

     NI_NOFQDN
         A fully qualified domain name is not required for local hosts.
         The local part of the fully qualified domain name is returned instead.

     NI_NUMERICHOST
         Return the address in numeric form, as if calling inet_ntop(3), instead of a host name.

     NI_NAMEREQD
       A name is required.
       If the host name cannot be found in DNS and this flag is set, a non-zero error code is returned.
       If the host name is not found and the flag is not set, the address is returned in numeric form.

     NI_NUMERICSERV
       The service name is returned as a digit string representing the port number.

     NI_DGRAM
          Specifies that the service being looked up is a datagram service, and causes getservbyport(3) to be called with a second argument of ``udp'' instead of its default of ``tcp''.
          This is required for the few ports(512-514) that have different services for UDP and TCP.

     This implementation allows numeric IPv6 address notation with scope identifier, as documented in chapter 11 of draft-ietf-ipv6-scoping-arch-02.txt.
     IPv6 link-local address will appear as a string like ``fe80::1%ne0''.
     Refer to getaddrinfo(3) for more information.

オプションの内容を全部読むのはちょっとしんどいかも。オプション以外の要点を整理すると、

  • 引数はsockaddr、socklen_t、char*、socklen_t、char*、socklen_t、flags の計7個
  • 最初のsockaddrは情報取得対象のsocket情報を格納したsockaddrで、次のsocklen_t はその長さ(?)
  • 3番目の引数「char*」にホスト名が格納され、4番目のsocklen_tがホスト名の長さ制限
  • 5番目の引数「char*」にサービス名が格納され、その制限が6番目のsocklen_t

という感じだろうか。

一応、C言語 ソケットプログラミング getnameinfoでIPとホスト名を調べるというサンプルを見つけているが、正直これだけでは自分にはよくわからない。やっぱりサンプル書いてみないとダメだが・・・今日は終わり。上の内容も正しいか、実際に動かして確認してみないといけない。