"socket" — 低水準ネットワークインターフェイス
*********************************************

This module provides access to the BSD *socket* interface. It is
available on all modern Unix systems, Windows, Mac OS X, BeOS, OS/2,
and probably additional platforms.

注釈: いくつかの挙動はプラットフォームに依存します。オペレーティング
  システ ムのソケットAPIを呼び出しているためです。

For an introduction to socket programming (in C), see the following
papers: An Introductory 4.3BSD Interprocess Communication Tutorial, by
Stuart Sechrest and An Advanced 4.3BSD Interprocess Communication
Tutorial, by Samuel J.  Leffler et al, both in the UNIX Programmer’s
Manual, Supplementary Documents 1 (sections PS1:7 and PS1:8).  The
platform-specific reference material for the various socket-related
system calls are also a valuable source of information on the details
of socket semantics.  For Unix, refer to the manual pages; for
Windows, see the WinSock (or Winsock 2) specification. For IPv6-ready
APIs, readers may want to refer to **RFC 3493** titled Basic Socket
Interface Extensions for IPv6.

Pythonインターフェースは、Unixのソケット用システムコールとライブラリイ
ンターフェースを、そのままPythonのオブジェクト指向スタイルに変換したも
のです。各種ソケット関連のシステムコールは、 "socket()" 関数で生成され
る *socket オブジェクト* のメソッドとして実装されています。 メソッドの
引数は C のインターフェイスよりも多少高水準で、例えばファイルに対する
"read()" や "write()" メソッドと同様に、 受信時のバッファ確保は自動的
に処理され、送信時のバッファ長は暗黙的に決まります。

Socket addresses are represented as follows: A single string is used
for the "AF_UNIX" address family. A pair "(host, port)" is used for
the "AF_INET" address family, where *host* is a string representing
either a hostname in Internet domain notation like "'daring.cwi.nl'"
or an IPv4 address like "'100.50.200.5'", and *port* is an integer.
For "AF_INET6" address family, a four-tuple "(host, port, flowinfo,
scopeid)" is used, where *flowinfo* and *scopeid* represents
"sin6_flowinfo" and "sin6_scope_id" member in "struct sockaddr_in6" in
C. For "socket" module methods, *flowinfo* and *scopeid* can be
omitted just for backward compatibility. Note, however, omission of
*scopeid* can cause problems in manipulating scoped IPv6 addresses.
Other address families are currently not supported. The address format
required by a particular socket object is automatically selected based
on the address family specified when the socket object was created.

For IPv4 addresses, two special forms are accepted instead of a host
address: the empty string represents "INADDR_ANY", and the string
"'<broadcast>'" represents "INADDR_BROADCAST". The behavior is not
available for IPv6 for backward compatibility, therefore, you may want
to avoid these if you intend to support IPv6 with your Python
programs.

IPv4/v6ソケットの *host* 部にホスト名を指定すると、処理結果が一定では
ない場合があります。これはPythonはDNSから取得したアドレスのうち最初の
アドレスを使用するので、 DNSの処理やホストの設定によって異なるIPv4/6ア
ドレスを取得する場合があるためです。常に同じ結果が必要であれば、
*host* に数値のアドレスを指定してください。

バージョン 2.5 で追加: AF_NETLINK sockets are represented as  pairs
"pid, groups".

バージョン 2.6 で追加: Linux-only support for TIPC is also available
using the "AF_TIPC" address family. TIPC is an open, non-IP based
networked protocol designed for use in clustered computer
environments.  Addresses are represented by a tuple, and the fields
depend on the address type. The general tuple form is "(addr_type, v1,
v2, v3 [, scope])", where:

* *addr_type* は "TIPC_ADDR_NAMESEQ", "TIPC_ADDR_NAME",
  "TIPC_ADDR_ID" の1つ。

* *scope* は "TIPC_ZONE_SCOPE", "TIPC_CLUSTER_SCOPE",
  "TIPC_NODE_SCOPE" の1つ。

* *addr_type* が "TIPC_ADDR_NAME" の場合、 *v1* はサーバータイプ、
  *v2* はポートID (the port identifier)、そして *v3* は 0 であるべきで
  す。

  *addr_type* が "TIPC_ADDR_NAMESEQ" の場合、 *v1* はサーバータイプ、
  *v2* はポート番号下位(lower port number)、 *v3* はポート番号上位
  (upper port number) です。

  *addr_type* が "TIPC_ADDR_ID" の場合、 *v1* はノード、 *v2* は参照、
  *v3* は0であるべきです。

All errors raise exceptions.  The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error "socket.error".

"setblocking()" メソッドで、非ブロッキングモードを使用することができま
す。また、より汎用的に "settimeout()" メソッドでタイムアウトを指定する
事ができます。

The module "socket" exports the following constants and functions:

exception socket.error

   This exception is raised for socket-related errors. The
   accompanying value is either a string telling what went wrong or a
   pair "(errno, string)" representing an error returned by a system
   call, similar to the value accompanying "os.error". See the module
   "errno", which contains names for the error codes defined by the
   underlying operating system.

   バージョン 2.6 で変更: "socket.error" is now a child class of
   "IOError".

exception socket.herror

   This exception is raised for address-related errors, i.e. for
   functions that use *h_errno* in the C API, including
   "gethostbyname_ex()" and "gethostbyaddr()".

   The accompanying value is a pair "(h_errno, string)" representing
   an error returned by a library call. *string* represents the
   description of *h_errno*, as returned by the "hstrerror()" C
   function.

exception socket.gaierror

   This exception is raised for address-related errors, for
   "getaddrinfo()" and "getnameinfo()". The accompanying value is a
   pair "(error, string)" representing an error returned by a library
   call. *string* represents the description of *error*, as returned
   by the "gai_strerror()" C function. The *error* value will match
   one of the "EAI_*" constants defined in this module.

exception socket.timeout

   This exception is raised when a timeout occurs on a socket which
   has had timeouts enabled via a prior call to "settimeout()".  The
   accompanying value is a string whose value is currently always 「
   timed out」.

   バージョン 2.3 で追加.

socket.AF_UNIX
socket.AF_INET
socket.AF_INET6

   These constants represent the address (and protocol) families, used
   for the first argument to "socket()".  If the "AF_UNIX" constant is
   not defined then this protocol is unsupported.

socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET

   These constants represent the socket types, used for the second
   argument to "socket()". (Only "SOCK_STREAM" and "SOCK_DGRAM" appear
   to be generally useful.)

SO_*
socket.SOMAXCONN
MSG_*
SOL_*
IPPROTO_*
IPPORT_*
INADDR_*
IP_*
IPV6_*
EAI_*
AI_*
NI_*
TCP_*

   Unixのソケット・IPプロトコルのドキュメントで定義されている各種定数
   。ソケットオブジェクトの "setsockopt()" や "getsockopt()" で使用し
   ます。ほとんどのシンボルはUnixのヘッダファイルに従っています。一部
   のシンボルには、デフォルト値を定義してあります。

SIO_*
RCVALL_*

   Windows の WSAIoctl() のための定数です。この定数はソケットオブジェ
   クトの "ioctl()" メソッドに引数として渡されます。

   バージョン 2.6 で追加.

TIPC_*

   TIPC 関連の定数で、C のソケットAPIが公開しているものにマッチします
   。詳しい情報は TIPC のドキュメントを参照してください。

   バージョン 2.6 で追加.

socket.has_ipv6

   現在のプラットフォームでIPv6がサポートされているか否かを示す真偽値
   。

   バージョン 2.3 で追加.

socket.create_connection(address[, timeout[, source_address]])

   *address* ("(host, port)" ペア) で listen しているTCPサービスに接続
   し、ソケットオブジェクトを返します。これは "socket.connect()" を高
   級にした関数です。 *host* が数値でないホスト名の場合、 "AF_INET" と
   "AF_INET6" の両方で名前解決を試み、得られた全てのアドレスに対して成
   功するまで接続を試みます。この関数を使って IPv4 と IPv6 に両対応し
   たクライアントを簡単に書くことができます。

   オプションの *timeout* 引数を指定すると、接続を試みる前にソケットオ
   ブジェクトのタイムアウトを設定します。 *timeout* が指定されない場合
   、 "getdefaulttimeout()" が返すデフォルトのタイムアウト設定値を利用
   します。

   *source_address* は接続する前にバインドするソースアドレスを指定する
   オプション引数で、指定する場合は "(host, port)" の2要素タプルでなけ
   ればなりません。 host や port が 『』 か 0 だった場合は、OSのデフォ
   ルトの動作になります。

   バージョン 2.6 で追加.

   バージョン 2.7 で変更: *source_address* が追加されました。

socket.getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]])

   *host* / *port* 引数の指すアドレス情報を、そのサービスに接続された
   ソケットを作成するために必要な全ての引数が入った 5 要素のタプルに変
   換します。 *host* はドメイン名、IPv4/v6アドレスの文字列、または
   "None" です。 *port* は "'http'" のようなサービス名文字列、ポート番
   号を表す数値、または "None" です。 *host* と *port* に "None" を指
   定すると C APIに "NULL" を渡せます。

   The *family*, *socktype* and *proto* arguments can be optionally
   specified in order to narrow the list of addresses returned.  By
   default, their value is "0", meaning that the full range of results
   is selected. The *flags* argument can be one or several of the
   "AI_*" constants, and will influence how results are computed and
   returned.  Its default value is "0".  For example, "AI_NUMERICHOST"
   will disable domain name resolution and will raise an error if
   *host* is a domain name.

   この関数は以下の構造をとる 5 要素のタプルのリストを返します:

   "(family, socktype, proto, canonname, sockaddr)"

   In these tuples, *family*, *socktype*, *proto* are all integers and
   are meant to be passed to the "socket()" function.  *canonname*
   will be a string representing the canonical name of the *host* if
   "AI_CANONNAME" is part of the *flags* argument; else *canonname*
   will be empty.  *sockaddr* is a tuple describing a socket address,
   whose format depends on the returned *family* (a "(address, port)"
   2-tuple for "AF_INET", a "(address, port, flow info, scope id)"
   4-tuple for "AF_INET6"), and is meant to be passed to the
   "socket.connect()" method.

   次の例では "example.org" の 80 番ポートポートへの TCP 接続を得るた
   めのアドレス情報を取得しようとしています。 (結果は IPv6 をサポート
   しているかどうかで変わります):

      >>> socket.getaddrinfo("example.org", 80, 0, 0, socket.IPPROTO_TCP)
      [(10, 1, 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
       (2, 1, 6, '', ('93.184.216.34', 80))]

   バージョン 2.2 で追加.

socket.getfqdn([name])

   *name* の完全修飾ドメイン名を返します。 *name* が空または省略された
   場合、ローカルホストを指定したとみなします。完全修飾ドメイン名の取
   得にはまず "gethostbyaddr()" でチェックし、次に可能であればエイリア
   スを調べ、名前にピリオドを含む最初の名前を値として返します。完全修
   飾ドメイン名を取得できない場合、 "gethostname()" で返されるホスト名
   を返します。

   バージョン 2.0 で追加.

socket.gethostbyname(hostname)

   ホスト名を "'100.50.200.5'" のようなIPv4形式のアドレスに変換します
   。ホスト名としてIPv4アドレスを指定した場合、その値は変換せずにその
   まま返ります。 "gethostbyname()" APIへのより完全なインターフェイス
   が必要であれば、 "gethostbyname_ex()" を参照してください。
   "gethostbyname()" は、IPv6名前解決をサポートしていません。IPv4/ v6
   のデュアルスタックをサポートする場合は "getaddrinfo()" を使用します
   。

socket.gethostbyname_ex(hostname)

   ホスト名から、IPv4形式の各種アドレス情報を取得します。戻り値は
   "(hostname, aliaslist, ipaddrlist)" のタプルで、 *hostname* は
   *ip_address* で指定したホストの正式名、 *aliaslist* は同じアドレス
   の別名のリスト(空の場合もある)、 *ipaddrlist* は同じホスト上の同一
   インターフェイスのIPv4アドレスのリスト(ほとんどの場合は単一のアドレ
   スのみ) を示します。 "gethostbyname_ex()" は、IPv6名前解決をサポー
   トしていません。IPv4/v6のデュアルスタックをサポートする場合は
   "getaddrinfo()" を使用します。

socket.gethostname()

   Pythonインタープリタを現在実行しているマシンのホスト名を含む文字列
   を返します。

   If you want to know the current machine’s IP address, you may want
   to use "gethostbyname(gethostname())". This operation assumes that
   there is a valid address-to-host mapping for the host, and the
   assumption does not always hold.

   Note: "gethostname()" doesn’t always return the fully qualified
   domain name; use "getfqdn()" (see above).

socket.gethostbyaddr(ip_address)

   "(hostname, aliaslist, ipaddrlist)" のタプルを返し、 *hostname* は
   *ip_address* で指定したホストの正式名、 *aliaslist* は同じアドレス
   の別名のリスト(空の場合もある)、 *ipaddrlist* は同じホスト上の同一
   インターフェイスのIPv4アドレスのリスト(ほとんどの場合は単一のアドレ
   スのみ)を示します。完全修飾ドメイン名が必要であれば、 "getfqdn()"
   を使用してください。 "gethostbyaddr()" は、IPv4/IPv6の両方をサポー
   トしています。

socket.getnameinfo(sockaddr, flags)

   ソケットアドレス *sockaddr* から、 "(host, port)" のタプルを取得し
   ます。 *flags* の設定に従い、 *host* は完全修飾ドメイン名または数値
   形式アドレスとなります。同様に、 *port* は文字列のポート名または数
   値のポート番号となります。

   バージョン 2.2 で追加.

socket.getprotobyname(protocolname)

   ("'icmp'" のような) インターネットプロトコル名を、 "socket()" の 第
   三引数として指定する事ができる定数に変換します。これは主にソケット
   を 「raw」 モード("SOCK_RAW")でオープンする場合には必要ですが、通常
   の ソケットモードでは第三引数に0を指定するか省略すれば正しいプロト
   コルが自動的に選択されます。

socket.getservbyname(servicename[, protocolname])

   インターネットサービス名とプロトコルから、そのサービスのポート番号
   を取得します。省略可能なプロトコル名として、 "'tcp'" か "'udp'" の
   どちらかを指定することができます。指定がなければどちらのプロトコル
   にもマッチします。

socket.getservbyport(port[, protocolname])

   インターネットポート番号とプロトコル名から、サービス名を取得します
   。省略可能なプロトコル名として、 "'tcp'" か "'udp'" のどちらかを指
   定することができます。指定がなければどちらのプロトコルにもマッチし
   ます。

socket.socket([family[, type[, proto]]])

   Create a new socket using the given address family, socket type and
   protocol number.  The address family should be "AF_INET" (the
   default), "AF_INET6" or "AF_UNIX".  The socket type should be
   "SOCK_STREAM" (the default), "SOCK_DGRAM" or perhaps one of the
   other "SOCK_" constants.  The protocol number is usually zero and
   may be omitted in that case.

socket.socketpair([family[, type[, proto]]])

   Build a pair of connected socket objects using the given address
   family, socket type, and protocol number.  Address family, socket
   type, and protocol number are as for the "socket()" function above.
   The default family is "AF_UNIX" if defined on the platform;
   otherwise, the default is "AF_INET". Availability: Unix.

   バージョン 2.4 で追加.

socket.fromfd(fd, family, type[, proto])

   Duplicate the file descriptor *fd* (an integer as returned by a
   file object’s "fileno()" method) and build a socket object from the
   result.  Address family, socket type and protocol number are as for
   the "socket()" function above. The file descriptor should refer to
   a socket, but this is not checked — subsequent operations on the
   object may fail if the file descriptor is invalid. This function is
   rarely needed, but can be used to get or set socket options on a
   socket passed to a program as standard input or output (such as a
   server started by the Unix inet daemon).  The socket is assumed to
   be in blocking mode. Availability: Unix.

socket.ntohl(x)

   32ビットの正の整数のバイトオーダを、ネットワークバイトオーダからホ
   ストバイトオーダに変換します。ホストバイトオーダとネットワークバイ
   トオーダが一致するマシンでは、この関数は何もしません。それ以外の場
   合は4バイトのスワップを行います。

socket.ntohs(x)

   16ビットの正の整数のバイトオーダを、ネットワークバイトオーダからホ
   ストバイトオーダに変換します。ホストバイトオーダとネットワークバイ
   トオーダが一致するマシンでは、この関数は何もしません。それ以外の場
   合は2バイトのスワップを行います。

socket.htonl(x)

   32ビットの正の整数のバイトオーダを、ホストバイトオーダからネットワ
   ークバイトオーダに変換します。ホストバイトオーダとネットワークバイ
   トオーダが一致するマシンでは、この関数は何もしません。それ以外の場
   合は4バイトのスワップを行います。

socket.htons(x)

   16ビットの正の整数のバイトオーダを、ホストバイトオーダからネットワ
   ークバイトオーダに変換します。ホストバイトオーダとネットワークバイ
   トオーダが一致するマシンでは、この関数は何もしません。それ以外の場
   合は2バイトのスワップを行います。

socket.inet_aton(ip_string)

   Convert an IPv4 address from dotted-quad string format (for
   example, 『123.45.67.89』) to 32-bit packed binary format, as a
   string four characters in length.  This is useful when conversing
   with a program that uses the standard C library and needs objects
   of type "struct in_addr", which is the C type for the 32-bit packed
   binary this function returns.

   "inet_aton()" はドットが 3 個以下の文字列も受け取ります; 詳細につい
   ては Unix のマニュアル *inet(3)* を参照してください。

   If the IPv4 address string passed to this function is invalid,
   "socket.error" will be raised. Note that exactly what is valid
   depends on the underlying C implementation of "inet_aton()".

   "inet_aton()" は、IPv6をサポートしません。IPv4/v6のデュアルスタック
   をサポートする場合は "inet_pton()" を使用します。

socket.inet_ntoa(packed_ip)

   Convert a 32-bit packed IPv4 address (a string four characters in
   length) to its standard dotted-quad string representation (for
   example, 『123.45.67.89』).  This is useful when conversing with a
   program that uses the standard C library and needs objects of type
   "struct in_addr", which is the C type for the 32-bit packed binary
   data this function takes as an argument.

   If the string passed to this function is not exactly 4 bytes in
   length, "socket.error" will be raised. "inet_ntoa()" does not
   support IPv6, and "inet_ntop()" should be used instead for IPv4/v6
   dual stack support.

socket.inet_pton(address_family, ip_string)

   IPアドレスを、アドレスファミリ固有の文字列からパックしたバイナリ形
   式に変換します。 "inet_pton()" は、 "struct in_addr" 型
   ("inet_aton()" と同様)や "struct in6_addr" を使用するライブラリやネ
   ットワークプロトコルを呼び出す際に使用することができます。

   Supported values for *address_family* are currently "AF_INET" and
   "AF_INET6". If the IP address string *ip_string* is invalid,
   "socket.error" will be raised. Note that exactly what is valid
   depends on both the value of *address_family* and the underlying
   implementation of "inet_pton()".

   Availability: Unix (maybe not all platforms).

   バージョン 2.3 で追加.

socket.inet_ntop(address_family, packed_ip)

   Convert a packed IP address (a string of some number of characters)
   to its standard, family-specific string representation (for
   example, "'7.10.0.5'" or "'5aef:2b::8'") "inet_ntop()" is useful
   when a library or network protocol returns an object of type
   "struct in_addr" (similar to "inet_ntoa()") or "struct in6_addr".

   Supported values for *address_family* are currently "AF_INET" and
   "AF_INET6". If the string *packed_ip* is not the correct length for
   the specified address family, "ValueError" will be raised.  A
   "socket.error" is raised for errors from the call to "inet_ntop()".

   Availability: Unix (maybe not all platforms).

   バージョン 2.3 で追加.

socket.getdefaulttimeout()

   新規に生成されたソケットオブジェクトの、デフォルトのタイムアウト値
   を浮動小数点形式の秒数で返します。タイムアウトを使用しない場合には
   "None" を返します。最初に socket モジュールがインポートされた時の初
   期値は "None" です。

   バージョン 2.3 で追加.

socket.setdefaulttimeout(timeout)

   Set the default timeout in seconds (float) for new socket objects.
   A value of "None" indicates that new socket objects have no
   timeout. When the socket module is first imported, the default is
   "None".

   バージョン 2.3 で追加.

socket.SocketType

   ソケットオブジェクトの型を示す型オブジェクト。 "type(socket(...))"
   と同じです。

参考:

  Module "SocketServer"
     ネットワークサーバの開発を省力化するためのクラス群。

  Module "ssl"
     ソケットオブジェクトに対する TLS/SSL ラッパー.


socket オブジェクト
===================

Socket objects have the following methods.  Except for "makefile()"
these correspond to Unix system calls applicable to sockets.

socket.accept()

   接続を受け付けます。ソケットはアドレスにbind済みで、listen中である
   必要があります。戻り値は "(conn, address)" のペアで、 *conn* は接続
   を通じてデータの送受信を行うための *新しい* ソケットオブジェクト、
   *address* は接続先でソケットにbindしているアドレスを示します。

socket.bind(address)

   ソケットを *address* にbindします。bind済みのソケットを再バインドす
   る事はできません。(*address* のフォーマットはアドレスファミリによっ
   て異なります – 前述。)

   注釈: This method has historically accepted a pair of parameters
     for "AF_INET" addresses instead of only a tuple.  This was never
     intentional and is no longer available in Python 2.0 and later.

socket.close()

   Close the socket.  All future operations on the socket object will
   fail. The remote end will receive no more data (after queued data
   is flushed). Sockets are automatically closed when they are
   garbage-collected.

   注釈: "close()" は接続に関連付けられたリソースを解放しますが、接
     続をす ぐに切断するとは限りません。接続を即座に切断したい場合は、
     "close()" の前に "shutdown()" を呼び出してください。

socket.connect(address)

   *address* で示されるリモートソケットに接続します。(*address* のフォ
   ーマットはアドレスファミリによって異なります — 前述。)

   注釈: This method has historically accepted a pair of parameters
     for "AF_INET" addresses instead of only a tuple.  This was never
     intentional and is no longer available in Python 2.0 and later.

socket.connect_ex(address)

   "connect(address)" と同様ですが、C言語の "connect()" 関数の呼び出し
   でエラーが発生した場合には例外を送出せずにエラーを戻り値として返し
   ます。(これ以外の、」host not found,」等のエラーの場合には例外が発
   生します。)処理が正常に終了した場合には "0" を返し、エラー時には
   "errno" の値を返します。この関数は、非同期接続をサポートする場合な
   どに使用することができます。

   注釈: This method has historically accepted a pair of parameters
     for "AF_INET" addresses instead of only a tuple. This was never
     intentional and is no longer available in Python 2.0 and later.

socket.fileno()

   Return the socket’s file descriptor (a small integer).  This is
   useful with "select.select()".

   Windowsではこのメソッドで返された小整数をファイル記述子を扱う箇所
   ("os.fdopen()" など) で利用できません。 Unix にはこの制限はありませ
   ん。

socket.getpeername()

   ソケットが接続しているリモートアドレスを返します。この関数は、リモ
   ート IPv4/v6ソケットのポート番号を調べる場合などに使用します。
   *address* のフォーマットはアドレスファミリによって異なります(前述)
   。この関数をサポートしていないシステムも存在します。

socket.getsockname()

   ソケット自身のアドレスを返します。この関数は、IPv4/v6ソケットのポー
   ト番号を調べる場合などに使用します。(*address* のフォーマットはアド
   レスファミリによって異なります — 前述。)

socket.getsockopt(level, optname[, buflen])

   Return the value of the given socket option (see the Unix man page
   *getsockopt(2)*).  The needed symbolic constants ("SO_*" etc.) are
   defined in this module.  If *buflen* is absent, an integer option
   is assumed and its integer value is returned by the function.  If
   *buflen* is present, it specifies the maximum length of the buffer
   used to receive the option in, and this buffer is returned as a
   string.  It is up to the caller to decode the contents of the
   buffer (see the optional built-in module "struct" for a way to
   decode C structures encoded as strings).

socket.ioctl(control, option)

   Platform:
      Windows

   "ioctl()" メソッドは WSAIoctl システムインタフェースへの制限された
   インタフェースです。詳しい情報については、 Win32 documentation を参
   照してください。

   他のプラットフォームでは一般的な "fcntl.fcntl()" と "fcntl.ioctl()"
   が使われるでしょう; これらの関数は第 1 引数としてソケットオブジェク
   トを取ります。

   バージョン 2.6 で追加.

socket.listen(backlog)

   Listen for connections made to the socket.  The *backlog* argument
   specifies the maximum number of queued connections and should be at
   least 0; the maximum value is system-dependent (usually 5), the
   minimum value is forced to 0.

socket.makefile([mode[, bufsize]])

   Return a *file object* associated with the socket.  (File objects
   are described in File Objects.) The file object does not close the
   socket explicitly when its "close()" method is called, but only
   removes its reference to the socket object, so that the socket will
   be closed if it is not referenced from anywhere else.

   The socket must be in blocking mode (it can not have a timeout).
   The optional *mode* and *bufsize* arguments are interpreted the
   same way as by the built-in "file()" function.

   注釈: Windows では "subprocess.Popen()" の stream 引数などファイ
     ルディ スクリプタつき file オブジェクトが期待されている場所では、
     "makefile()" によって作成される file-like オブジェクトは使用でき
     ません。

socket.recv(bufsize[, flags])

   Receive data from the socket.  The return value is a string
   representing the data received.  The maximum amount of data to be
   received at once is specified by *bufsize*.  See the Unix manual
   page *recv(2)* for the meaning of the optional argument *flags*; it
   defaults to zero.

   注釈: ハードウェアおよびネットワークの現実に最大限マッチするよう
     に、 *bufsize* の値は比較的小さい2の累乗、たとえば 4096、にすべき
     です 。

socket.recvfrom(bufsize[, flags])

   Receive data from the socket.  The return value is a pair "(string,
   address)" where *string* is a string representing the data received
   and *address* is the address of the socket sending the data.  See
   the Unix manual page *recv(2)* for the meaning of the optional
   argument *flags*; it defaults to zero. (The format of *address*
   depends on the address family — see above.)

socket.recvfrom_into(buffer[, nbytes[, flags]])

   Receive data from the socket, writing it into *buffer* instead of
   creating a new string.  The return value is a pair "(nbytes,
   address)" where *nbytes* is the number of bytes received and
   *address* is the address of the socket sending the data.  See the
   Unix manual page *recv(2)* for the meaning of the optional argument
   *flags*; it defaults to zero.  (The format of *address* depends on
   the address family — see above.)

   バージョン 2.5 で追加.

socket.recv_into(buffer[, nbytes[, flags]])

   Receive up to *nbytes* bytes from the socket, storing the data into
   a buffer rather than creating a new string.  If *nbytes* is not
   specified (or 0), receive up to the size available in the given
   buffer.  Returns the number of bytes received.  See the Unix manual
   page *recv(2)* for the meaning of the optional argument *flags*; it
   defaults to zero.

   バージョン 2.5 で追加.

socket.send(string[, flags])

   Send data to the socket.  The socket must be connected to a remote
   socket.  The optional *flags* argument has the same meaning as for
   "recv()" above. Returns the number of bytes sent. Applications are
   responsible for checking that all data has been sent; if only some
   of the data was transmitted, the application needs to attempt
   delivery of the remaining data. For further information on this
   concept, consult the ソケットプログラミング HOWTO.

socket.sendall(string[, flags])

   Send data to the socket.  The socket must be connected to a remote
   socket.  The optional *flags* argument has the same meaning as for
   "recv()" above. Unlike "send()", this method continues to send data
   from *string* until either all data has been sent or an error
   occurs.  "None" is returned on success.  On error, an exception is
   raised, and there is no way to determine how much data, if any, was
   successfully sent.

socket.sendto(string, address)
socket.sendto(string, flags, address)

   ソケットにデータを送信します。このメソッドでは接続先を *address* で
   指定するので、接続済みではいけません。オプション引数 *flags* の意味
   は、上記 "recv()" と同じです。戻り値として、送信したバイト数を返し
   ます。(*address* のフォーマットはアドレスファミリによって異なります
   — 前述。)

socket.setblocking(flag)

   Set blocking or non-blocking mode of the socket: if *flag* is 0,
   the socket is set to non-blocking, else to blocking mode.
   Initially all sockets are in blocking mode.  In non-blocking mode,
   if a "recv()" call doesn’t find any data, or if a "send()" call
   can’t immediately dispose of the data, an "error" exception is
   raised; in blocking mode, the calls block until they can proceed.
   "s.setblocking(0)" is equivalent to "s.settimeout(0.0)";
   "s.setblocking(1)" is equivalent to "s.settimeout(None)".

socket.settimeout(value)

   Set a timeout on blocking socket operations.  The *value* argument
   can be a nonnegative float expressing seconds, or "None". If a
   float is given, subsequent socket operations will raise a "timeout"
   exception if the timeout period *value* has elapsed before the
   operation has completed.  Setting a timeout of "None" disables
   timeouts on socket operations. "s.settimeout(0.0)" is equivalent to
   "s.setblocking(0)"; "s.settimeout(None)" is equivalent to
   "s.setblocking(1)".

   バージョン 2.3 で追加.

socket.gettimeout()

   ソケットに指定されたタイムアウト値を取得します。タイムアウト値が設
   定されている場合には浮動小数点型で秒数が、設定されていなければ
   "None" が返ります。この値は、最後に呼び出された "setblocking()" ま
   たは "settimeout()" によって設定されます。

   バージョン 2.3 で追加.

Some notes on socket blocking and timeouts: A socket object can be in
one of three modes: blocking, non-blocking, or timeout.  Sockets are
always created in blocking mode.  In blocking mode, operations block
until complete or the system returns an error (such as connection
timed out).  In non-blocking mode, operations fail (with an error that
is unfortunately system-dependent) if they cannot be completed
immediately.  In timeout mode, operations fail if they cannot be
completed within the timeout specified for the socket or if the system
returns an error.  The "setblocking()" method is simply a shorthand
for certain "settimeout()" calls.

Timeout mode internally sets the socket in non-blocking mode.  The
blocking and timeout modes are shared between file descriptors and
socket objects that refer to the same network endpoint.  A consequence
of this is that file objects returned by the "makefile()" method must
only be used when the socket is in blocking mode; in timeout or non-
blocking mode file operations that cannot be completed immediately
will fail.

Note that the "connect()" operation is subject to the timeout setting,
and in general it is recommended to call "settimeout()" before calling
"connect()" or pass a timeout parameter to "create_connection()".  The
system network stack may return a connection timeout error of its own
regardless of any Python socket timeout setting.

socket.setsockopt(level, optname, value)

   Set the value of the given socket option (see the Unix manual page
   *setsockopt(2)*).  The needed symbolic constants are defined in the
   "socket" module ("SO_*" etc.).  The value can be an integer or a
   string representing a buffer.  In the latter case it is up to the
   caller to ensure that the string contains the proper bits (see the
   optional built-in module "struct" for a way to encode C structures
   as strings).

socket.shutdown(how)

   Shut down one or both halves of the connection.  If *how* is
   "SHUT_RD", further receives are disallowed.  If *how* is "SHUT_WR",
   further sends are disallowed.  If *how* is "SHUT_RDWR", further
   sends and receives are disallowed.  Depending on the platform,
   shutting down one half of the connection can also close the
   opposite half (e.g. on Mac OS X, "shutdown(SHUT_WR)" does not allow
   further reads on the other end of the connection).

"read()" メソッドと "write()" メソッドは存在しませんので注意してくださ
い。代わりに *flags* を省略した "recv()" と "send()" を使うことができ
ます。

ソケットオブジェクトには以下の "socket" コンストラクタに渡された値に対
応した (読み出し専用) 属性があります。

socket.family

   ソケットファミリー。

   バージョン 2.5 で追加.

socket.type

   ソケットタイプ。

   バージョン 2.5 で追加.

socket.proto

   ソケットプロトコル。

   バージョン 2.5 で追加.


使用例
======

以下は TCP/IP プロトコルの簡単なサンプルとして、受信したデータをクライ
アントにそのまま返送するサーバ (接続可能なクライアントは一件のみ) と、
サーバに接続するクライアントの例を示します。サーバでは、 "socket()" ・
"bind()" ・ "listen()" ・ "accept()" を実行し (複数のクライアントから
の接続を受け付ける場合、 "accept()" を複数回呼び出します)、クライアン
トでは "socket()" と "connect()" だけを呼び出しています。サーバでは
"sendall()" / "recv()" メソッドは listen 中のソケットで実行するのでは
なく、 "accept()" で取得したソケットに対して実行している点にも注意して
ください。

次のクライアントとサーバは、IPv4 のみをサポートしています。

   # Echo server program
   import socket

   HOST = ''                 # Symbolic name meaning all available interfaces
   PORT = 50007              # Arbitrary non-privileged port
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.bind((HOST, PORT))
   s.listen(1)
   conn, addr = s.accept()
   print 'Connected by', addr
   while 1:
       data = conn.recv(1024)
       if not data: break
       conn.sendall(data)
   conn.close()

   # Echo client program
   import socket

   HOST = 'daring.cwi.nl'    # The remote host
   PORT = 50007              # The same port as used by the server
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.connect((HOST, PORT))
   s.sendall('Hello, world')
   data = s.recv(1024)
   s.close()
   print 'Received', repr(data)

次のサンプルは上記のサンプルとほとんど同じですが、IPv4 と IPv6 の両方
をサポートしています。サーバでは、IPv4/v6 の両方ではなく、利用可能な最
初のアドレスファミリだけを listen しています。ほとんどの IPv6 対応シス
テムでは IPv6 が先に現れるため、サーバは IPv4 には応答しません。クライ
アントでは名前解決の結果として取得したアドレスに順次接続を試み、最初に
接続に成功したソケットにデータを送信しています。

   # Echo server program
   import socket
   import sys

   HOST = None               # Symbolic name meaning all available interfaces
   PORT = 50007              # Arbitrary non-privileged port
   s = None
   for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
       af, socktype, proto, canonname, sa = res
       try:
           s = socket.socket(af, socktype, proto)
       except socket.error as msg:
           s = None
           continue
       try:
           s.bind(sa)
           s.listen(1)
       except socket.error as msg:
           s.close()
           s = None
           continue
       break
   if s is None:
       print 'could not open socket'
       sys.exit(1)
   conn, addr = s.accept()
   print 'Connected by', addr
   while 1:
       data = conn.recv(1024)
       if not data: break
       conn.send(data)
   conn.close()

   # Echo client program
   import socket
   import sys

   HOST = 'daring.cwi.nl'    # The remote host
   PORT = 50007              # The same port as used by the server
   s = None
   for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
       af, socktype, proto, canonname, sa = res
       try:
           s = socket.socket(af, socktype, proto)
       except socket.error as msg:
           s = None
           continue
       try:
           s.connect(sa)
       except socket.error as msg:
           s.close()
           s = None
           continue
       break
   if s is None:
       print 'could not open socket'
       sys.exit(1)
   s.sendall('Hello, world')
   data = s.recv(1024)
   s.close()
   print 'Received', repr(data)

The last example shows how to write a very simple network sniffer with
raw sockets on Windows. The example requires administrator privileges
to modify the interface:

   import socket

   # the public network interface
   HOST = socket.gethostbyname(socket.gethostname())

   # create a raw socket and bind it to the public interface
   s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
   s.bind((HOST, 0))

   # Include IP headers
   s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

   # receive all packages
   s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

   # receive a package
   print s.recvfrom(65565)

   # disabled promiscuous mode
   s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)

この例を、ほとんど間を空けずに複数回実行すると、以下のエラーが発生する
場合があります:

   socket.error: [Errno 98] Address already in use

これは以前の実行がソケットを "TIME_WAIT" 状態のままにし、すぐには再利
用できないことで起こります。

これを防ぐのに、 "socket" フラグの "socket.SO_REUSEADDR" があります:

   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
   s.bind((HOST, PORT))

"SO_REUSEADDR" フラグは、 "TIME_WAIT" 状態にあるローカルソケットをその
タイムアウト期限が自然に切れるのを待つことなく再利用することをカーネル
に伝えます。
