OSDN Git Service

(split) LDP: Release pages for LDP v3.39.
[linuxjm/LDP_man-pages.git] / release / man3 / getaddrinfo.3
1 .\" Copyright (c) 2007, 2008 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\" and Copyright (c) 2006 Ulrich Drepper <drepper@redhat.com>
3 .\" A few pieces of an earlier version remain:
4 .\" Copyright 2000, Sam Varshavchik <mrsam@courier-mta.com>
5 .\"
6 .\" Permission is granted to make and distribute verbatim copies of this
7 .\" manual provided the copyright notice and this permission notice are
8 .\" preserved on all copies.
9 .\"
10 .\" Permission is granted to copy and distribute modified versions of this
11 .\" manual under the conditions for verbatim copying, provided that the
12 .\" entire resulting derived work is distributed under the terms of a
13 .\" permission notice identical to this one.
14 .\"
15 .\" Since the Linux kernel and libraries are constantly changing, this
16 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
17 .\" responsibility for errors or omissions, or for damages resulting from
18 .\" the use of the information contained herein.  The author(s) may not
19 .\" have taken the same level of care in the production of this manual,
20 .\" which is licensed free of charge, as they might when working
21 .\" professionally.
22 .\"
23 .\" Formatted or processed versions of this manual, if unaccompanied by
24 .\" the source, must acknowledge the copyright and authors of this work.
25 .\"
26 .\" References: RFC 2553
27 .\"
28 .\" 2005-08-09, mtk, added AI_ALL, AI_ADDRCONFIG, AI_V4MAPPED,
29 .\"                     and AI_NUMERICSERV.
30 .\" 2006-11-25, Ulrich Drepper <drepper@redhat.com>
31 .\"     Add text describing Internationalized Domain Name extensions.
32 .\" 2007-06-08, mtk: added example programs
33 .\" 2008-02-26, mtk; clarify discussion of NULL 'hints' argument; other
34 .\"     minor rewrites.
35 .\" 2008-06-18, mtk: many parts rewritten
36 .\" 2008-12-04, Petr Baudis <pasky@suse.cz>
37 .\"     Describe results ordering and reference /etc/gai.conf.
38 .\" FIXME . glibc's 2.9 NEWS file documents DCCP and UDP-lite support
39 .\"           and is SCTP support now also there?
40 .\"
41 .\"*******************************************************************
42 .\"
43 .\" This file was generated with po4a. Translate the source file.
44 .\"
45 .\"*******************************************************************
46 .TH GETADDRINFO 3 2012\-04\-14 GNU "Linux Programmer's Manual"
47 .SH 名前
48 getaddrinfo, freeaddrinfo, gai_strerror \- ネットワークのアドレスとサービスを変換する
49 .SH 書式
50 .nf
51 \fB#include <sys/types.h>\fP
52 \fB#include <sys/socket.h>\fP
53 \fB#include <netdb.h>\fP
54 .sp
55 \fBint getaddrinfo(const char *\fP\fInode\fP\fB, const char *\fP\fIservice\fP\fB,\fP
56 \fB                const struct addrinfo *\fP\fIhints\fP\fB,\fP
57 \fB                struct addrinfo **\fP\fIres\fP\fB);\fP
58 .sp
59 \fBvoid freeaddrinfo(struct addrinfo *\fP\fIres\fP\fB);\fP
60 .sp
61 \fBconst char *gai_strerror(int \fP\fIerrcode\fP\fB);\fP
62 .fi
63 .sp
64 .in -4n
65 glibc 向けの機能検査マクロの要件 (\fBfeature_test_macros\fP(7)  参照):
66 .ad l
67 .in
68 .sp
69 \fBgetaddrinfo\fP(), \fBfreeaddrinfo\fP(), \fBgai_strerror\fP():
70 .RS 4
71 _POSIX_C_SOURCE\ >=\ 1 || _XOPEN_SOURCE || _POSIX_SOURCE
72 .RE
73 .ad b
74 .SH 説明
75 .\" .BR getipnodebyname (3),
76 .\" .BR getipnodebyaddr (3),
77 \fBgetaddrinfo\fP()  は、(インターネットのホストとサービスを識別する)  \fInode\fP と \fIservice\fP を渡すと、一つ以上の
78 \fIaddrinfo\fP 構造体を返す。それぞれの \fIaddrinfo\fP 構造体には、 \fBbind\fP(2)  や \fBconnect\fP(2)
79 を呼び出す際に指定できるインターネットアドレスが格納されている。 \fBgetaddrinfo\fP()  関数は、 \fBgetservbyname\fP(3)
80 と \fBgetservbyport\fP(3)  の機能をまとめて一つのインターフェースにしたものであるが、 これらの関数と違い、
81 \fBgetaddrinfo\fP()  はリエントラントであり、 \fBgetaddrinfo\fP()  を使うことでプログラムは IPv4 と IPv6
82 の違いに関する依存関係を なくすことができる。
83 .PP
84 \fBgetaddrinfo\fP()  が用いる \fIaddrinfo\fP 構造体は以下のフィールドを含む。
85 .sp
86 .in +4n
87 .nf
88 struct addrinfo {
89     int              ai_flags;
90     int              ai_family;
91     int              ai_socktype;
92     int              ai_protocol;
93     socklen_t        ai_addrlen;
94     struct sockaddr *ai_addr;
95     char            *ai_canonname;
96     struct addrinfo *ai_next;
97 };
98 .fi
99 .in
100 .PP
101 \fIhints\fP 引き数は \fIaddrinfo\fP 構造体を指し示し、この構造体を用いて \fIres\fP
102 が指すリストに入れて返すソケットアドレス構造体を選択するための基準を指定する。 \fIhints\fP が NULL でない場合、 \fIhints\fP は
103 \fIaddrinfo\fP 構造体を指し示し、その構造体のフィールド \fIai_family\fP, \fIai_socktype\fP,
104 \fIai_protocol\fP で \fBgetaddrinfo\fP()  が返すソケットアドレス集合に対する基準を指定する。
105 .TP  12
106 \fIai_family\fP
107 このフィールドは返されるアドレスの希望のアドレスファミリーを指定する。 このフィールドに指定できる有効な値としては \fBAF_INET\fP と
108 \fBAF_INET6\fP がある。 また、値 \fBAF_UNSPEC\fP を指定すると、 \fBgetaddrinfo\fP()  は \fInode\fP と
109 \fIservice\fP で使用できるいずれかのアドレスファミリー (例えば IPv4 か IPv6) の ソケットアドレスを返すことを求められる。
110 .TP 
111 \fIai_socktype\fP
112 このフィールドは推奨のソケット型 (例えば \fBSOCK_STREAM\fP や \fBSOCK_DGRAM\fP)  を指定する。 このフィールドに 0
113 を指定すると、任意のソケット型のソケットアドレスを \fBgetaddrinfo\fP()  が返してよいことを意味する。
114 .TP 
115 \fIai_protocol\fP
116 このフィールドは返されるソケットアドレスのプロトコルを指定する。 このフィールドに 0 を指定すると、任意のプロトコルののソケットアドレスを
117 \fBgetaddrinfo\fP()  が返してよいことを意味する。
118 .TP 
119 \fIai_flags\fP
120 このフィールドは、追加のオプション (下記) を指定する。 複数のフラグを指定する際には、それらのビット単位の OR をとって指定する。
121 .PP
122 \fIhints\fP が指し示す構造体の他のすべてのフィールドには 0 か NULL ポインタを適切に入れなければならない。 \fIhints\fP に NULL
123 を指定するのは、 \fIai_socktype\fP と \fIai_protocol\fP に 0 を、 \fIai_family\fP に \fBAF_UNSPEC\fP
124 を、 \fIai_flags\fP に \fB(AI_V4MAPPED\ |\ AI_ADDRCONFIG)\fP を設定するのと等価である。
125
126 \fInode\fP には、数値形式のネットワークアドレス (IPv4 の場合は \fBinet_aton\fP(3)
127 でサポートされているドット区切りの数字による表記、 IPv6 の場合は \fBinet_pton\fP(3)  でサポートされている 16 進数の文字列形式)
128 もしくは ネットワークホスト名を指定する。 ネットワークホスト名を指定した場合には、そのネットワークアドレスが検索され、 名前解決が行なわれる。
129 \fIhints.ai_flags\fP に \fBAI_NUMERICHOST\fP フラグが含まれている場合は、 \fInode\fP
130 は数値形式のネットワークアドレスでなければならない。 \fBAI_NUMERICHOST\fP
131 フラグを使うと、時間の掛かる可能性のあるネットワークホストアドレスの検索は すべて抑制される。
132 .PP
133 \fIhints.ai_flags\fP に \fBAI_PASSIVE\fP フラグが指定され、かつ \fInode\fP が NULL の場合、
134 返されるソケットアドレスは コネクションを \fBaccept\fP(2)  するためのソケットを \fBbind\fP(2)  するのに適したものとなる。
135 返されるソケットアドレスには「ワイルドカード・アドレス」 (IPv4 アドレスの場合は \fBINADDR_ANY\fP、 IPv6 アドレスの場合は
136 \fBIN6ADDR_ANY_INIT\fP)  が入る。 ワイルドカード・アドレスは、任意のホストのネットワークアドレスで接続を
137 受け付けようとするアプリケーション (通常はサーバー) で用いられる。 \fInode\fP が NULL でない場合、 \fBAI_PASSIVE\fP
138 フラグは無視される。
139 .PP
140 \fIhints.ai_flags\fP に \fBAI_PASSIVE\fP フラグがセットされていない場合、 返されるソケットアドレスは
141 \fBconnect\fP(2), \fBsendto\fP(2), \fBsendmsg\fP(2)  での使用に適したものとなる。 \fInode\fP が NULL
142 の場合、ネットワークアドレスにはループバック・インターフェイスの アドレス (IPv4 アドレスの場合は \fBINADDR_LOOPBACK\fP IPv6
143 アドレスの場合は \fBIN6ADDR_LOOPBACK_INIT\fP)\fBが設定される。\fP これは同じホスト上で動作している接続相手と通信するような
144 アプリケーションで用いられる。
145 .PP
146 \fIservice\fP により、返される各アドレス構造体のポート番号が決まる。 この引き数がサービス名 (\fBservices\fP(5)  参照)
147 の場合、対応するポート番号に翻訳される。 この引き数には 10 進数も指定することができ、 この場合にはバイナリへの変換だけが行われる。
148 \fIservice\fP が NULL の場合、返されるソケットアドレスのポート番号は 初期化されないままとなる。 \fIhints.ai_flags\fP に
149 \fBAI_NUMERICSERV\fP が指定され、かつ \fIservice\fP が NULL でない場合、 \fIservice\fP
150 は数値のポート番号を含む文字列を指し示さなければならない。 このフラグは、名前解決サービスが不要であることが分かっている場合に、
151 サービスの起動を抑制するために用いられる。
152 .PP
153 \fInode\fP と \fIservice\fP のどちらかは NULL にしてよいが、両方同時に NULL にしてはならない。
154 .PP
155 \fBgetaddrinfo\fP()  関数は、 \fIaddrinfo\fP 構造体のメモリ確保を行い、 \fIaddrinfo\fP
156 構造体のリンクリストを初期化し、 \fIres\fP にリストの先頭へのポインタを入れて返す。 このとき、各構造体のネットワークアドレスは \fInode\fP と
157 \fIservice\fP に一致し、 \fIhints\fP で課されたすべての制限を満たすものとなる。 リンクリストの要素は \fIai_next\fP
158 フィールドにより連結される。
159
160 リンクリストの \fIaddrinfo\fP 構造体は複数個になることもあり、その理由はいくつかある。 ネットワークホストがマルチホームである、
161 複数のプロトコルでアクセスできる (例えば \fBAF_INET\fP と \fBAF_INET6\fP の両方) 、 複数のソケット種別で同じサービスが利用できる
162 (例えば、ひとつが \fBSOCK_STREM\fP アドレスで、もうひとつが \fBSOCK_DGRAM\fP アドレスである)、がある。
163 通常は、アプリケーションは返された順序でアドレスを試すべきである。 \fBgetaddrinfo\fP()  の中で使用される並べ替え関数は RFC\ 3484 で定義されている。 特殊なシステムでは、 \fI/etc/gai.conf\fP を編集することで、この順序を微調整することができる
164 (\fI/etc/gai.conf\fP は glibc 2.5 以降で利用できる)。
165 .PP
166 .\" In glibc prior to 2.3.4, the ai_canonname of each addrinfo
167 .\" structure was set pointing to the canonical name; that was
168 .\" more than POSIX.1-2001 specified, or other implementations provided.
169 .\" MTK, Aug 05
170 \fIhints.ai_flags\fP に \fBAI_CANONNAME\fP フラグが含まれている場合、返されるリストの最初の \fIaddrinfo\fP
171 構造体の \fIai_canonname\fP フィールドはホストの公式な名前を指すように設定される。
172
173 返される各々の \fIaddrinfo\fP 構造体の残りのフィールドは以下のように初期化される。
174 .IP * 2
175 \fIai_family\fP, \fIai_socktype\fP, \fIai_protocol\fP フィールドはソケット生成パラメータを返す
176 (これらのフィールドの意味は \fBsocket\fP(2)  の同じ名前の引き数と同じである)。 例えば、 \fIai_family\fP は
177 \fBAF_INET\fP や \fBAF_INET6\fP を返し、 \fIai_socktype\fP は \fBSOCK_DGRAM\fP や
178 \fBSOCK_STREAM\fP を返し、 \fIai_protocol\fP はそのソケットのプロトコルを返す。
179 .IP *
180 \fIai_addr\fP フィールドにはソケットアドレスへのポインタが書き込まれ、 \fIai_addrlen\fP
181 フィールドにはソケットアドレスの長さがバイト単位で書き込まれる。
182 .PP
183 \fIhints.ai_flags\fP が \fBAI_ADDRCONFIG\fP を含む場合、 \fIres\fP が指すリストには、 ローカルシステムに最低一つの
184 IPv4 アドレスが設定されている場合は IPv4 アドレスが返され、 ローカルシステムに最低一つの IPv6 アドレスが設定されている場合は IPv6
185 アドレスが返される。
186 .PP
187 \fIhint.ai_flags\fP に \fBAI_V4MAPPED\fP が指定されていて、 \fIhints.ai_family\fP に \fBAF_INET6\fP
188 が指定され、 マッチする IPv6 アドレスが見つからなかった場合、 \fIres\fP が指すリストには IPv4\-mapped IPv6
189 アドレスが返される。 \fIhints.ai_flags\fP に \fBAI_V4MAPPED\fP と \fBAI_ALL\fP の両方が指定されている場合、
190 \fIres\fP が指すリストには IPv6 アドレスと IPv4\-mapped IPv6 アドレスの 両方が返される。 \fBAI_V4MAPPED\fP
191 が指定されていない場合、 \fBAI_ALL\fP は無視される。
192 .PP
193 \fBfreeaddrinfo\fP()  関数は、 リンクリスト \fIres\fP に対して動的に割り当てられたメモリを解放する。
194 .SS "国際化ドメイン名のための getaddrinfo() の拡張"
195 .PP
196 glibc 2.3.4 から、 \fBgetaddrinfo\fP()  は入出力するホスト名を透過的に国際化ドメイン名 (IDN) 形式 (RFC 3490
197 の \fIInternationalizing Domain Names in Applications (IDNA)\fP を参照のこと)
198 と変換することを選択的に認めるように拡張されている。 4 つの新しいフラグが定義されている:
199 .TP 
200 \fBAI_IDN\fP
201 このフラグが指定されると、 \fInode\fP で与えられたノード名は必要があれば IDN 形式に変換される。
202 ソース符号化形式は現在のロケールのものである。
203
204 .\" Implementation Detail:
205 .\" To minimize effects on system performance the implementation might
206 .\" want to check whether the input string contains any non-ASCII
207 .\" characters.  If there are none the IDN step can be skipped completely.
208 .\" On systems which allow not-ASCII safe encodings for a locale this
209 .\" might be a problem.
210 入力名に非 ASCII 文字が含まれている場合、 IDN 符号化形式が使われる。 非 ASCII
211 文字が含まれている(ピリオドで区切られる)部分ノード名は、 名前解決機能に渡される前に ASCII 互換符号化形式 (ACE) を使って 符号化される。
212 .TP 
213 \fBAI_CANONIDN\fP
214 \fBAI_CANONNAME\fP が指定されている場合、 \fBgetaddrinfo\fP()  は名前の検索に成功した後、 返された \fIaddrinfo\fP
215 構造体に対応するノードの正規名を返す。 返り値は名前解決機能から返された値の正確なコピーである。
216
217 .\"
218 .\"Implementation Detail:
219 .\"If no component of the returned name starts with xn\-\- the IDN
220 .\"step can be skipped, therefore avoiding unnecessary slowdowns.
221 \fBAI_CANONIDN\fP 名前が ACE で符号化されている場合、一つまたは複数の名前の構成要素の先頭に \fIxn\-\-\fP を含んでいる。
222 これらの構成要素を読み込み可能な形に変換するために、 \fBAI_CANONNAME\fP と共に \fBAI_CANONIDN\fP フラグを渡すことも出来る。
223 返される文字列は現在のロケールの符号化形式で符号化されている。
224 .TP 
225 \fBAI_IDN_ALLOW_UNASSIGNED\fP, \fBAI_IDN_USE_STD3_ASCII_RULES\fP
226 これらのフラグをセットすると、IDNA 処理で使用されるフラグ IDNA_ALLOW_UNASSIGNED (未割り当ての Unicode
227 のコードポイントを許容) と IDNA_USE_STD3_ASCII_RULES (出力が STD3 準拠のホスト名かをチェックする)
228 がそれぞれ有効になる。
229 .SH 返り値
230 .\" FIXME glibc defines the following additional errors, some which
231 .\" can probably be returned by getaddrinfo(); they need to
232 .\" be documented.
233 .\" #ifdef __USE_GNU
234 .\" #define EAI_INPROGRESS  -100  /* Processing request in progress.  */
235 .\" #define EAI_CANCELED    -101  /* Request canceled.  */
236 .\" #define EAI_NOTCANCELED -102  /* Request not canceled.  */
237 .\" #define EAI_ALLDONE     -103  /* All requests done.  */
238 .\" #define EAI_INTR        -104  /* Interrupted by a signal.  */
239 .\" #define EAI_IDN_ENCODE  -105  /* IDN encoding failed.  */
240 .\" #endif
241 \fBgetaddrinfo\fP()  は成功すると 0 を返し、失敗すると以下の非 0 のエラーコードのいずれかを返す。
242 .TP 
243 \fBEAI_ADDRFAMILY\fP
244 .\" Not in SUSv3
245 指定されたネットワークホストには、 要求されたアドレスファミリーのネットワークアドレスがない。
246 .TP 
247 \fBEAI_AGAIN\fP
248 ネームサーバーから一時的な失敗 (temporary failure)  を意味する返事が返された。後でもう一度試してみよ。
249 .TP 
250 \fBEAI_BADFLAGS\fP
251 \fIhints.ai_flags\fP のフラグに不正なフラグが含まれている。または、 \fIhints.ai_flags\fP に
252 \fBAI_CANONNAME\fP が含まれていて、かつ \fIname\fP が NULL であった。
253 .TP 
254 \fBEAI_FAIL\fP
255 ネームサーバーから恒久的な失敗 (permanent failure)  を意味する返事が返された。
256 .TP 
257 \fBEAI_FAMILY\fP
258 要求されたアドレスファミリーがサポートされていない。
259 .TP 
260 \fBEAI_MEMORY\fP
261 メモリが足りない。
262 .TP 
263 \fBEAI_NODATA\fP
264 .\" Not in SUSv3
265 指定されたネットワークホストは存在するが、 ネットワークアドレスがひとつも定義されていない。
266 .TP 
267 \fBEAI_NONAME\fP
268 \fInode\fP と \fIservice\fP のどちらかが不明、または \fInode\fP と \fIservice\fP の両方が NULL だった場合、または
269 \fBAI_NUMERICSERV\fP が \fIhints.ai_flags\fP に指定されていて、 \fIhints.ai_flags\fP と
270 \fIservice\fP が数値のポート番号の文字列でない。
271 .TP 
272 \fBEAI_SERVICE\fP
273 要求されたサービスは、要求されたソケットタイプでは利用できない。 他のソケットタイプでなら利用可能かもしれない。 このエラーが発生する例としては、
274 \fIservice\fP が "shell" (ストリーム・ソケットでのみ利用できるサービス) で、 \fIhints.ai_protocol\fP に
275 \fBIPPROTO_UDP\fP が指定されたり、 \fIhints.ai_socktype\fP に \fBSOCK_DGRAM\fP が指定されたりした場合がある。
276 また、 \fIservice\fP が NULL 以外で、 \fIhints.ai_socktype\fP に \fBSOCK_RAW\fP
277 (サービスの考え方をサポートしていないソケット種別)  が指定された場合にも、このエラーが発生する。
278 .TP 
279 \fBEAI_SOCKTYPE\fP
280 要求されたソケットタイプがサポートされていない。 このエラーが発生する例としては、 \fIhints.ai_socktype\fP と
281 \fIhints.ai_protocol\fP が矛盾している場合 (例えば \fIhints.ai_socktype\fP が \fBSOCK_DGRAM\fP で
282 \fIhints.ai_protocol\fP が \fBIPPROTO_TCP\fP)  がある。
283 .TP 
284 \fBEAI_SYSTEM\fP
285 その他のシステムエラー。詳しくは \fIerrno\fP を調べること。
286 .PP
287 \fBgai_strerror\fP()  関数を用いると、これらのエラーコードを人間に可読な文字列に変換できるので、 エラー報告に適するだろう。
288 .SH ファイル
289 \fI/etc/gai.conf\fP
290 .SH 準拠
291 POSIX.1\-2001.  \fBgetaddrinfo\fP()  関数は RFC 2553 に記載されている。
292 .SH 注意
293 \fBgetaddrinfo\fP()  は、IPv6 scope\-ID を指定するために \fIaddress\fP\fB%\fP\fIscope\-id\fP
294 記法をサポートしている。
295
296 \fBAI_ADDRCONFIG\fP, \fBAI_ALL\fP, \fBAI_V4MAPPED\fP は glibc 2.3.3 以降で利用可能である。
297 \fBAI_NUMERICSERV\fP は glibc 2.3.4 以降で利用可能である。
298
299 POSIX.1\-2001 によると、 \fIhints\fP に NULL が指定された場合、 \fIai_flags\fP を 0 とみなすべきとされている。
300 GNU C ライブラリでは、この場合に、代わりに \fIai_flags\fP を \fB(AI_V4MAPPED\ |\ AI_ADDRCONFIG)\fP
301 とみなすようになっている。 この値の方が標準規格の改善になると考えられているからである。
302 .SH 例
303 .\" getnameinfo.3 refers to this example
304 .\" socket.2 refers to this example
305 .\" bind.2 refers to this example
306 .\" connect.2 refers to this example
307 .\" recvfrom.2 refers to this example
308 .\" sendto.2 refers to this example
309 以下のプログラムは、 \fBgetaddrinfo\fP(), \fBgai_strerror\fP(), \fBfreeaddrinfo\fP(),
310 \fBgetnameinfo\fP(3)  の使い方を示したものである。 プログラムは UDP データグラムの echo サーバとクライアントである。
311 .SS サーバのプログラム
312 \&
313 .nf
314 #include <sys/types.h>
315 #include <stdio.h>
316 #include <stdlib.h> 
317 #include <unistd.h>
318 #include <string.h>
319 #include <sys/socket.h>
320 #include <netdb.h>
321
322 #define BUF_SIZE 500
323
324 int
325 main(int argc, char *argv[])
326 {
327     struct addrinfo hints;
328     struct addrinfo *result, *rp;
329     int sfd, s;
330     struct sockaddr_storage peer_addr;
331     socklen_t peer_addr_len;
332     ssize_t nread;
333     char buf[BUF_SIZE];
334
335     if (argc != 2) {
336         fprintf(stderr, "Usage: %s port\en", argv[0]);
337         exit(EXIT_FAILURE);
338     }
339
340     memset(&hints, 0, sizeof(struct addrinfo));
341     hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
342     hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
343     hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
344     hints.ai_protocol = 0;          /* Any protocol */
345     hints.ai_canonname = NULL;
346     hints.ai_addr = NULL;
347     hints.ai_next = NULL;
348
349     s = getaddrinfo(NULL, argv[1], &hints, &result);
350     if (s != 0) {
351         fprintf(stderr, "getaddrinfo: %s\en", gai_strerror(s));
352         exit(EXIT_FAILURE);
353     }
354
355     /* getaddrinfo() returns a list of address structures.
356        Try each address until we successfully bind(2).
357        If socket(2) (or bind(2)) fails, we (close the socket
358        and) try the next address. */
359
360     for (rp = result; rp != NULL; rp = rp\->ai_next) {
361         sfd = socket(rp\->ai_family, rp\->ai_socktype,
362                 rp\->ai_protocol);
363         if (sfd == \-1)
364             continue;
365
366         if (bind(sfd, rp\->ai_addr, rp\->ai_addrlen) == 0)
367             break;                  /* Success */
368
369         close(sfd);
370     }
371
372     if (rp == NULL) {               /* No address succeeded */
373         fprintf(stderr, "Could not bind\en");
374         exit(EXIT_FAILURE);
375     }
376
377     freeaddrinfo(result);           /* No longer needed */
378
379     /* Read datagrams and echo them back to sender */
380
381     for (;;) {
382         peer_addr_len = sizeof(struct sockaddr_storage);
383         nread = recvfrom(sfd, buf, BUF_SIZE, 0,
384                 (struct sockaddr *) &peer_addr, &peer_addr_len);
385         if (nread == \-1)
386             continue;               /* Ignore failed request */
387
388         char host[NI_MAXHOST], service[NI_MAXSERV];
389
390         s = getnameinfo((struct sockaddr *) &peer_addr,
391                         peer_addr_len, host, NI_MAXHOST,
392                         service, NI_MAXSERV, NI_NUMERICSERV);
393        if (s == 0)
394             printf("Received %ld bytes from %s:%s\en",
395                     (long) nread, host, service);
396         else
397             fprintf(stderr, "getnameinfo: %s\en", gai_strerror(s));
398
399         if (sendto(sfd, buf, nread, 0,
400                     (struct sockaddr *) &peer_addr,
401                     peer_addr_len) != nread)
402             fprintf(stderr, "Error sending response\en");
403     }
404 }
405 .fi
406 .SS クライアントのプログラム
407 \&
408 .nf
409 #include <sys/types.h>
410 #include <sys/socket.h>
411 #include <netdb.h>
412 #include <stdio.h>
413 #include <stdlib.h>
414 #include <unistd.h>
415 #include <string.h>
416
417 #define BUF_SIZE 500
418
419 int
420 main(int argc, char *argv[])
421 {
422     struct addrinfo hints;
423     struct addrinfo *result, *rp;
424     int sfd, s, j;
425     size_t len;
426     ssize_t nread;
427     char buf[BUF_SIZE];
428
429     if (argc < 3) {
430         fprintf(stderr, "Usage: %s host port msg...\en", argv[0]);
431         exit(EXIT_FAILURE);
432     }
433
434     /* Obtain address(es) matching host/port */
435
436     memset(&hints, 0, sizeof(struct addrinfo));
437     hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
438     hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
439     hints.ai_flags = 0;
440     hints.ai_protocol = 0;          /* Any protocol */
441
442     s = getaddrinfo(argv[1], argv[2], &hints, &result);
443     if (s != 0) {
444         fprintf(stderr, "getaddrinfo: %s\en", gai_strerror(s));
445         exit(EXIT_FAILURE);
446     }
447
448     /* getaddrinfo() returns a list of address structures.
449        Try each address until we successfully connect(2).
450        If socket(2) (or connect(2)) fails, we (close the socket
451        and) try the next address. */
452
453     for (rp = result; rp != NULL; rp = rp\->ai_next) {
454         sfd = socket(rp\->ai_family, rp\->ai_socktype,
455                      rp\->ai_protocol);
456         if (sfd == \-1)
457             continue;
458
459         if (connect(sfd, rp\->ai_addr, rp\->ai_addrlen) != \-1)
460             break;                  /* Success */
461
462         close(sfd);
463     }
464
465     if (rp == NULL) {               /* No address succeeded */
466         fprintf(stderr, "Could not connect\en");
467         exit(EXIT_FAILURE);
468     }
469
470     freeaddrinfo(result);           /* No longer needed */
471
472     /* Send remaining command\-line arguments as separate
473        datagrams, and read responses from server */
474
475     for (j = 3; j < argc; j++) {
476         len = strlen(argv[j]) + 1;
477                 /* +1 for terminating null byte */
478
479         if (len + 1 > BUF_SIZE) {
480             fprintf(stderr,
481                     "Ignoring long message in argument %d\en", j);
482             continue;
483         }
484
485         if (write(sfd, argv[j], len) != len) {
486             fprintf(stderr, "partial/failed write\en");
487             exit(EXIT_FAILURE);
488         }
489
490         nread = read(sfd, buf, BUF_SIZE);
491         if (nread == \-1) {
492             perror("read");
493             exit(EXIT_FAILURE);
494         }
495
496         printf("Received %ld bytes: %s\en", (long) nread, buf);
497     }
498
499     exit(EXIT_SUCCESS);
500 }
501 .fi
502 .SH 関連項目
503 .\" .BR getipnodebyaddr (3),
504 .\" .BR getipnodebyname (3),
505 \fBgetaddrinfo_a\fP(3), \fBgethostbyname\fP(3), \fBgetnameinfo\fP(3), \fBinet\fP(3),
506 \fBhostname\fP(7), \fBip\fP(7)