"socket" --- Low-level networking interface
*******************************************

**소스 코드:** Lib/socket.py

======================================================================

이 모듈은 BSD *socket* 인터페이스에 대한 액세스를 제공합니다. 모든 현
대 유닉스 시스템, 윈도우, MacOS, 그리고 아마 추가 플랫폼에서 사용할 수
있습니다.

참고:

  호출이 운영 체제 소켓 API로 이루어지기 때문에, 일부 동작은 플랫폼에
  따라 다를 수 있습니다.

가용성: not WASI.

이 모듈은 웹어셈블리에서 작동하지 않거나 제공되지 않습니다. 자세한 내
용은 웹어셈블리 플랫폼을 참조하세요.

The Python interface is a straightforward transliteration of the Unix
system call and library interface for sockets to Python's object-
oriented style: the "socket()" function returns a *socket object*
whose methods implement the various socket system calls.  Parameter
types are somewhat higher-level than in the C interface: as with
"read()" and "write()" operations on Python files, buffer allocation
on receive operations is automatic, and buffer length is implicit on
send operations.

더 보기:

  모듈 "socketserver"
     네트워크 서버 작성을 단순화하는 클래스.

  모듈 "ssl"
     소켓 객체용 TLS/SSL 래퍼.


소켓 패밀리
===========

시스템과 빌드 옵션에 따라, 다양한 소켓 패밀리가 이 모듈에서 지원됩니다
.

특정 소켓 객체가 요구하는 주소 형식은 소켓 객체를 만들 때 지정된 주소
패밀리에 따라 자동으로 선택됩니다. 소켓 주소는 다음과 같이 표현됩니다:

* 파일 시스템 노드에 바인드 된 "AF_UNIX" 소켓의 주소는 파일 시스템 인
  코딩과 "'surrogateescape'" 에러 처리기(**PEP 383**을 참조하세요)를
  사용하는 문자열로 표현됩니다. 리눅스의 추상 이름 공간(abstract
  namespace)에 있는 주소는 처음에 널 바이트가 있는 *바이트열류 객체*로
  반환됩니다; 이 이름 공간의 소켓은 일반 파일 시스템 소켓과 통신 할 수
  있으므로, 리눅스에서 실행하려는 프로그램은 두 가지 유형의 주소를 모
  두 다뤄야 할 수도 있습니다. 문자열이나 바이트열류 객체는 인자로 전달
  할 때 두 가지 유형의 주소에 모두 사용할 수 있습니다.

  버전 3.3에서 변경: 이전에는, "AF_UNIX" 소켓 경로가 UTF-8 인코딩을 사
  용한다고 가정했습니다.

  버전 3.5에서 변경: 이제 쓰기 가능한 *바이트열류 객체*를 받아들입니다
  .

* 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.

  * IPv4 주소의 경우, 호스트 주소 대신 두 개의 특수 형식이 허용됩니다:
    "''"는 모든 인터페이스에 바인딩하는 데 사용되는 "INADDR_ANY"를 나
    타내며 "'<broadcast>'" 문자열은 "INADDR_BROADCAST"를 나타냅니다.
    이 동작은 IPv6와 호환되지 않으므로, 여러분의 파이썬 프로그램에서
    IPv6를 지원하려는 경우에는 이것들을 사용하지 않을 수 있습니다.

* "AF_INET6" 주소 패밀리의 경우, 4-튜플 "(host, port, flowinfo,
  scope_id)"가 사용됩니다. 여기서 *flowinfo* 와 *scope_id*는 C에서
  "struct sockaddr_in6"의 "sin6_flowinfo" 와 "sin6_scope_id" 멤버를 나
  타냅니다. "socket" 모듈 메서드의 경우, *flowinfo* 와 *scope_id*는 이
  전 버전과의 호환성을 위해 생략할 수 있습니다. 그러나, *scope_id*를
  생략하면 스코프가 지정된(scoped) IPv6 주소를 조작하는 데 문제가 발생
  할 수 있습니다.

  버전 3.7에서 변경: 멀티캐스트 주소(의미 있는 *scope_id*를 가진)의 경
  우, *address*에는 "%scope_id" (또는 "zone id") 부분이 포함될 수 없습
  니다. 이 정보는 불필요하므로 안전하게 생략할 수 있습니다 (권장 사항
  ).

* "AF_NETLINK" 소켓은 "(pid, groups)" 쌍으로 표현됩니다.

* TIPC에 대한 리눅스 전용 지원은 "AF_TIPC" 주소 패밀리를 사용하여 사용
  할 수 있습니다. TIPC는 클러스터 된 컴퓨터 환경에서 사용하도록 설계된
  개방형 비 IP 기반 네트워크 프로토콜입니다. 주소는 튜플로 표현되며 필
  드는 주소 유형에 따라 다릅니다. 일반적인 튜플 형식은 "(addr_type,
  v1, v2, v3 [, scope])"입니다. 이때:

  * *addr_type*은 "TIPC_ADDR_NAMESEQ", "TIPC_ADDR_NAME" 또는
    "TIPC_ADDR_ID" 중 하나입니다.

  * *scope*는 "TIPC_ZONE_SCOPE", "TIPC_CLUSTER_SCOPE" 또는
    "TIPC_NODE_SCOPE" 중 하나입니다.

  * *addr_type*이 "TIPC_ADDR_NAME"이면, *v1*은 서버 유형이고, *v2*는
    포트 식별자이며, *v3*은 0이어야 합니다.

    *addr_type*이 "TIPC_ADDR_NAMESEQ"면, *v1*은 서버 유형이고, *v2*는
    하위 포트 번호이며, *v3*는 상위 포트 번호입니다.

    *addr_type*이 "TIPC_ADDR_ID"면, *v1*은 노드이고, *v2*는 참조이며,
    *v3*는 0으로 설정되어야 합니다.

* 튜플 "(interface, )"가 "AF_CAN" 주소 패밀리에 사용됩니다. 여기서
  *interface*는 "'can0'"과 같은 네트워크 인터페이스 이름을 나타내는 문
  자열입니다. 네트워크 인터페이스 이름 "''"는 이 패밀리의 모든 네트워
  크 인터페이스에서 패킷을 수신하는 데 사용할 수 있습니다.

  * "CAN_ISOTP" 프로토콜은 튜플 "(interface, rx_addr, tx_addr)"를 요구
    하는데, 두 개의 추가 매개 변수는 모두 CAN 식별자(표준 또는 확장)를
    나타내는 부호 없는 long 정수입니다.

  * "CAN_J1939" 프로토콜에는 "(interface, name, pgn, addr)"가 필요한데
    , 여기서 추가 파라미터는 ECU 이름을 나타내는 64 비트 부호 없는 정
    수, PGN(Parameter Group Number)을 나타내는 32비트 부호 없는 정수
    및 주소를 나타내는 8비트 정수입니다.

* A string or a tuple "(id, unit)" is used for the "SYSPROTO_CONTROL"
  protocol of the "PF_SYSTEM" family. The string is the name of a
  kernel control using a dynamically assigned ID. The tuple can be
  used if ID and unit number of the kernel control are known or if a
  registered ID is used.

  Added in version 3.3.

* "AF_BLUETOOTH"는 다음 프로토콜 및 주소 형식을 지원합니다:

  * "BTPROTO_L2CAP" accepts a tuple "(bdaddr, psm[, cid[,
    bdaddr_type]])" where:

    * "bdaddr" is a string specifying the Bluetooth address.

    * "psm" is an integer specifying the Protocol/Service Multiplexer.

    * "cid" is an optional integer specifying the Channel Identifier.
      If not given, defaults to zero.

    * "bdaddr_type" is an optional integer specifying the address
      type; one of "BDADDR_BREDR" (default), "BDADDR_LE_PUBLIC",
      "BDADDR_LE_RANDOM".

    버전 3.14에서 변경: Added "cid" and "bdaddr_type" fields.

  * "BTPROTO_RFCOMM"은 "(bdaddr, channel)"를 받아들입니다. 여기서
    "bdaddr"은 문자열 블루투스 주소이고 "channel"은 정수입니다.

  * "BTPROTO_HCI" accepts a format that depends on your OS.

    * On Linux it accepts an integer "device_id" or a tuple
      "(device_id, [channel])" where "device_id" specifies the number
      of the Bluetooth device, and "channel" is an optional integer
      specifying the HCI channel ("HCI_CHANNEL_RAW" by default).

    * On FreeBSD, NetBSD and DragonFly BSD it accepts "bdaddr" where
      "bdaddr" is the Bluetooth address as a string.

    버전 3.2에서 변경: NetBSD 및 DragonFlyBSD 지원이 추가되었습니다.

    버전 3.13.3에서 변경: FreeBSD support added.

    버전 3.14에서 변경: Added "channel" field. "device_id" not packed
    in a tuple is now accepted.

  * "BTPROTO_SCO" accepts "bdaddr" where "bdaddr" is the Bluetooth
    address as a string or a "bytes" object. (ex.
    "'12:23:34:45:56:67'" or "b'12:23:34:45:56:67'")

    버전 3.14에서 변경: FreeBSD support added.

* "AF_ALG"는 커널 암호 인터페이스에 기반한 리눅스 전용 소켓입니다. 알
  고리즘 소켓은 2~4개의 요소를 갖는 "(type, name [, feat [, mask]])"
  튜플로 구성됩니다. 여기서:

  * *type*은 문자열의 알고리즘 유형입니다, 예를 들어, "aead", "hash",
    "skcipher" 또는 "rng".

  * *name*은 알고리즘 이름과 연산 모드 문자열입니다, 예를 들어,
    "sha256", "hmac(sha256)", "cbc(aes)" 또는 "drbg_nopr_ctr_aes256".

  * *feat* 과 *mask*는 부호 없는 32비트 정수입니다.

  가용성: Linux >= 2.6.38.

  Some algorithm types require more recent Kernels.

  Added in version 3.6.

* "AF_VSOCK"은 가상 기계와 호스트가 통신할 수 있게 합니다. 소켓은
  "(CID, port)" 튜플로 표현되는데, 컨텍스트 ID 또는 CID와 port는 정수
  입니다.

  가용성: Linux >= 3.9

  See *vsock(7)*

  Added in version 3.7.

* "AF_PACKET" is a low-level interface directly to network devices.
  The addresses are represented by the tuple "(ifname, proto[,
  pkttype[, hatype[, addr]]])" where:

  * *ifname* - 장치 이름을 지정하는 문자열

  * *proto* - The Ethernet protocol number. May be "ETH_P_ALL" to
    capture all protocols, one of the ETHERTYPE_* constants or any
    other Ethernet protocol number.

  * *pkttype* - 패킷 유형을 지정하는 선택적 정수.:

    * "PACKET_HOST" (기본값) - 로컬 호스트로 향하는 패킷.

    * "PACKET_BROADCAST" - 물리 계층 브로드캐스트 패킷.

    * "PACKET_MULTICAST" - Packet sent to a physical-layer multicast
      address.

    * "PACKET_OTHERHOST" - 무차별 모드의 장치 관리자에 의해 포착된 다
      른 호스트로 향하는 패킷.

    * "PACKET_OUTGOING" - 패킷 소켓으로 루프 백 된 로컬 호스트에서 시
      작된 패킷.

  * *hatype* - ARP 하드웨어 주소 유형을 지정하는 선택적 정수.

  * *addr* - 하드웨어 물리 주소를 지정하는 선택적 바이트열류 객체, 해
    석은 장치에 따라 다릅니다.

  가용성: Linux >= 2.2.

* "AF_QIPCRTR"는 Qualcomm 플랫폼의 코 프로세서에서 실행되는 서비스와
  통신하기 위한 리눅스 전용 소켓 기반 인터페이스입니다. 주소 패밀리는
  "(node, port)" 튜플로 표현되는데, *node*와 *port*는 음수가 아닌 정수
  입니다.

  가용성: Linux >= 4.7.

  Added in version 3.8.

* "IPPROTO_UDPLITE"는 UDP의 변형으로, 체크섬으로 커버되는 패킷 부분을
  지정할 수 있습니다. 변경할 수 있는 두 개의 소켓 옵션이 추가되었습니
  다. "self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length)"는
  체크섬으로 커버되는 나가는 패킷 부분을 변경하고
  "self.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length)"는 너
  무 적은 데이터를 커버하는 패킷을 걸러냅니다. 두 경우 모두 "length"는
  "range(8, 2**16, 8)"에 있어야합니다.

  이러한 소켓은 IPv4의 경우 "socket(AF_INET, SOCK_DGRAM,
  IPPROTO_UDPLITE)" 또는 IPv6의 경우 "socket(AF_INET6, SOCK_DGRAM,
  IPPROTO_UDPLITE)"로 구성되어야 합니다.

  가용성: Linux >= 2.6.20, FreeBSD >= 10.1

  Added in version 3.9.

* "AF_HYPERV" is a Windows-only socket based interface for
  communicating with Hyper-V hosts and guests. The address family is
  represented as a "(vm_id, service_id)" tuple where the "vm_id" and
  "service_id" are UUID strings.

  The "vm_id" is the virtual machine identifier or a set of known VMID
  values if the target is not a specific virtual machine. Known VMID
  constants defined on "socket" are:

  * "HV_GUID_ZERO"

  * "HV_GUID_BROADCAST"

  * "HV_GUID_WILDCARD" - Used to bind on itself and accept connections
    from all partitions.

  * "HV_GUID_CHILDREN" - Used to bind on itself and accept connection
    from child partitions.

  * "HV_GUID_LOOPBACK" - Used as a target to itself.

  * "HV_GUID_PARENT" - When used as a bind accepts connection from the
    parent partition. When used as an address target it will connect
    to the parent partition.

  The "service_id" is the service identifier of the registered
  service.

  Added in version 3.12.

IPv4/v6 소켓 주소의 *host* 부분에 호스트 명을 사용하면, 파이썬이 DNS
결정에서 반환된 첫 번째 주소를 사용하기 때문에, 프로그램은 비결정적인
동작을 보일 수 있습니다. 소켓 주소는 DNS 결정 결과 및/또는 호스트 구성
에 따라 실제 IPv4/v6 주소로 다르게 결정됩니다. 결정론적 동작을 위해서
는 *host* 부분에 숫자 주소를 사용하십시오.

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 "OSError" or one of its
subclasses.

비 블로킹 모드는 "setblocking()"을 통해 지원됩니다. 시간제한을 기반으
로 하는 일반화는 "settimeout()"을 통해 지원됩니다.


모듈 내용
=========

모듈 "socket"은 다음 요소를 노출합니다.


예외
----

exception socket.error

   "OSError"의 폐지된 별칭.

   버전 3.3에서 변경: **PEP 3151**을 따라, 이 클래스는 "OSError"의 별
   칭이 되었습니다.

exception socket.herror

   "OSError"의 서브 클래스, 이 예외는 주소 관련 에러에서 발생합니다.
   즉 "gethostbyname_ex()"와 "gethostbyaddr()"를 포함하는 POSIX C API
   의 *h_errno*를 사용하는 함수들. 수반되는 값은 라이브러리 호출이 반
   환한 에러를 나타내는 "(h_errno, string)" 쌍입니다. *h_errno*는 숫자
   값이고, *string*은 "hstrerror()" C 함수에 의해 반환된 *h_errno*의
   설명을 나타냅니다.

   버전 3.3에서 변경: 이 클래스는 "OSError"의 서브 클래스가 되었습니다
   .

exception socket.gaierror

   A subclass of "OSError", this exception is raised for address-
   related errors by "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 numeric *error* value will match one of the "EAI_*"
   constants defined in this module.

   버전 3.3에서 변경: 이 클래스는 "OSError"의 서브 클래스가 되었습니다
   .

exception socket.timeout

   A deprecated alias of "TimeoutError".

   "OSError"의 서브 클래스, 이 예외는 앞서 "settimeout()" 호출을 통해
   (또는 묵시적으로 "setdefaulttimeout()"를 통해) 시간제한이 활성화된
   소켓에서 시간 초과가 일어날 때 발생합니다. 수반되는 값은 현재는 항
   상 "timed out" 값을 갖는 문자열입니다.

   버전 3.3에서 변경: 이 클래스는 "OSError"의 서브 클래스가 되었습니다
   .

   버전 3.10에서 변경: This class was made an alias of "TimeoutError".


상수
----

AF_* 와 SOCK_* 상수는 이제 "AddressFamily" 와 "SocketKind" "IntEnum"
컬렉션입니다.

Added in version 3.4.

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.  More constants may
   be available depending on the system.

socket.AF_UNSPEC

   "AF_UNSPEC" means that "getaddrinfo()" should return socket
   addresses for any address family (either IPv4, IPv6, or any other)
   that can be used.

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()".  More constants may be available depending
   on the system. (Only "SOCK_STREAM" and "SOCK_DGRAM" appear to be
   generally useful.)

socket.SOCK_CLOEXEC
socket.SOCK_NONBLOCK

   이 두 상수는, 정의되었다면, 소켓 유형과 결합하여 일부 플래그를 원자
   적으로 설정할 수 있도록 합니다 (따라서 경쟁 조건의 가능성과 별도 호
   출의 필요성을 피할 수 있습니다).

   더 보기:

     Secure File Descriptor Handling for a more thorough explanation.

   가용성: Linux >= 2.6.27.

   Added in version 3.2.

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

   Many constants of these forms, documented in the Unix documentation
   on sockets and/or the IP protocol, are also defined in the socket
   module. They are generally used in arguments to the "setsockopt()"
   and "getsockopt()" methods of socket objects.  In most cases, only
   those symbols that are defined in the Unix header files are
   defined; for a few symbols, default values are provided.

   버전 3.6에서 변경: "SO_DOMAIN", "SO_PROTOCOL", "SO_PEERSEC",
   "SO_PASSSEC", "TCP_USER_TIMEOUT", "TCP_CONGESTION"가 추가되었습니다
   .

   버전 3.6.5에서 변경: Added support for "TCP_FASTOPEN",
   "TCP_KEEPCNT" on Windows platforms when available.

   버전 3.7에서 변경: "TCP_NOTSENT_LOWAT"가 추가되었습니다.Added
   support for "TCP_KEEPIDLE", "TCP_KEEPINTVL" on Windows platforms
   when available.

   버전 3.10에서 변경: "IP_RECVTOS" was added.  Added "TCP_KEEPALIVE".
   On MacOS this constant can be used in the same  way that
   "TCP_KEEPIDLE" is used on Linux.

   버전 3.11에서 변경: Added "TCP_CONNECTION_INFO". On MacOS this
   constant can be used in the same way that "TCP_INFO" is used on
   Linux and BSD.

   버전 3.12에서 변경: Added "SO_RTABLE" and "SO_USER_COOKIE". On
   OpenBSD and FreeBSD respectively those constants can be used in the
   same way that "SO_MARK" is used on Linux. Also added missing TCP
   socket options from Linux: "TCP_MD5SIG",
   "TCP_THIN_LINEAR_TIMEOUTS", "TCP_THIN_DUPACK", "TCP_REPAIR",
   "TCP_REPAIR_QUEUE", "TCP_QUEUE_SEQ", "TCP_REPAIR_OPTIONS",
   "TCP_TIMESTAMP", "TCP_CC_INFO", "TCP_SAVE_SYN", "TCP_SAVED_SYN",
   "TCP_REPAIR_WINDOW", "TCP_FASTOPEN_CONNECT", "TCP_ULP",
   "TCP_MD5SIG_EXT", "TCP_FASTOPEN_KEY", "TCP_FASTOPEN_NO_COOKIE",
   "TCP_ZEROCOPY_RECEIVE", "TCP_INQ", "TCP_TX_DELAY". Added
   "IP_PKTINFO", "IP_UNBLOCK_SOURCE", "IP_BLOCK_SOURCE",
   "IP_ADD_SOURCE_MEMBERSHIP", "IP_DROP_SOURCE_MEMBERSHIP".

   버전 3.13에서 변경: Added "SO_BINDTOIFINDEX". On Linux this
   constant can be used in the same way that "SO_BINDTODEVICE" is
   used, but with the index of a network interface instead of its
   name.

   버전 3.14에서 변경: Added missing "IP_FREEBIND", "IP_RECVERR",
   "IPV6_RECVERR", "IP_RECVTTL", and "IP_RECVORIGDSTADDR" on Linux.

   버전 3.14에서 변경: Added support for "TCP_QUICKACK" on Windows
   platforms when available.

socket.AF_CAN
socket.PF_CAN
SOL_CAN_*
CAN_*

   리눅스 설명서에 설명되어있는 이 형식의 많은 상수는 소켓 모듈에도 정
   의되어 있습니다.

   가용성: Linux >= 2.6.25, NetBSD >= 8.

   Added in version 3.3.

   버전 3.11에서 변경: NetBSD support was added.

   버전 3.14에서 변경: Restored missing "CAN_RAW_ERR_FILTER" on Linux.

socket.CAN_BCM
CAN_BCM_*

   CAN 프로토콜 패밀리에서 CAN_BCM은 브로드캐스트 관리자 (Broadcast
   Manager, BCM) 프로토콜입니다. 리눅스 설명서에서 설명된 브로드캐스트
   관리자 상수도 소켓 모듈에 정의되어 있습니다.

   가용성: Linux >= 2.6.25.

   참고:

     "CAN_BCM_CAN_FD_FRAME" 플래그는 리눅스 >= 4.8 에서만 사용 가능합
     니다.

   Added in version 3.4.

socket.CAN_RAW_FD_FRAMES

   CAN_RAW 소켓에서 CAN FD 지원을 활성화합니다. 기본적으로 비활성화되
   어 있습니다. 여러분의 응용 프로그램이 CAN과 CAN FD 프레임을 모두 보
   낼 수 있도록 합니다; 그러나 소켓에서 읽을 때 CAN과 CAN FD 프레임을
   모두 받아들여야 합니다.

   이 상수는 리눅스 설명서에 설명되어 있습니다.

   가용성: Linux >= 3.6.

   Added in version 3.5.

socket.CAN_RAW_JOIN_FILTERS

   주어진 모든 CAN 필터와 일치하는 CAN 프레임 만 사용자 공간으로 전달
   되도록 적용된 CAN 필터를 결합합니다.

   이 상수는 리눅스 설명서에 설명되어 있습니다.

   가용성: Linux >= 4.1.

   Added in version 3.9.

socket.CAN_ISOTP

   CAN 프로토콜 패밀리의 CAN_ISOTP는 ISO-TP (ISO 15765-2) 프로토콜입니
   다. ISO-TP 상수는 리눅스 설명서에 설명되어 있습니다.

   가용성: Linux >= 2.6.25.

   Added in version 3.7.

socket.CAN_J1939

   CAN 프로토콜 패밀리의 CAN_J1939는 SAE J1939 프로토콜입니다. J1939
   상수는 리눅스 설명서에 설명되어 있습니다.

   가용성: Linux >= 5.4.

   Added in version 3.9.

socket.AF_DIVERT
socket.PF_DIVERT

   These two constants, documented in the FreeBSD divert(4) manual
   page, are also defined in the socket module.

   가용성: FreeBSD >= 14.0.

   Added in version 3.12.

socket.AF_PACKET
socket.PF_PACKET
PACKET_*

   리눅스 설명서에 설명되어있는 이 형식의 많은 상수는 소켓 모듈에도 정
   의되어 있습니다.

   가용성: Linux >= 2.2.

socket.ETH_P_ALL

   "ETH_P_ALL" can be used in the "socket" constructor as *proto* for
   the "AF_PACKET" family in order to capture every packet, regardless
   of protocol.

   For more information, see the *packet(7)* manpage.

   가용성: Linux.

   Added in version 3.12.

socket.AF_RDS
socket.PF_RDS
socket.SOL_RDS
RDS_*

   리눅스 설명서에 설명되어있는 이 형식의 많은 상수는 소켓 모듈에도 정
   의되어 있습니다.

   가용성: Linux >= 2.6.30.

   Added in version 3.3.

socket.SIO_RCVALL
socket.SIO_KEEPALIVE_VALS
socket.SIO_LOOPBACK_FAST_PATH
RCVALL_*

   윈도우 WSAIoctl()용 상수. 이 상수는 소켓 객체의 "ioctl()" 메서드에
   대한 인자로 사용됩니다.

   버전 3.6에서 변경: "SIO_LOOPBACK_FAST_PATH"가 추가되었습니다.

TIPC_*

   TIPC 관련 상수. C 소켓 API에서 내보낸 것과 일치합니다. 자세한 정보
   는 TIPC 설명서를 참조하십시오.

socket.AF_ALG
socket.SOL_ALG
ALG_*

   리눅스 커널 암호화용 상수.

   가용성: Linux >= 2.6.38.

   Added in version 3.6.

socket.AF_VSOCK
socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID
VMADDR*
SO_VM*

   리눅스 호스트/게스트 통신용 상수.

   가용성: Linux >= 4.8.

   Added in version 3.7.

socket.AF_LINK

   가용성: BSD, macOS.

   Added in version 3.4.

socket.has_ipv6

   이 상수는 이 플랫폼에서 IPv6가 지원되는지를 나타내는 논릿값을 포함
   합니다.

socket.AF_BLUETOOTH
socket.BTPROTO_L2CAP
socket.BTPROTO_RFCOMM
socket.BTPROTO_HCI
socket.BTPROTO_SCO

   Integer constants for use with Bluetooth addresses.

socket.BDADDR_ANY
socket.BDADDR_LOCAL

   이들은 특수한 의미를 지닌 블루투스 주소를 포함하는 문자열 상수입니
   다. 예를 들어, "BDADDR_ANY"는 바인딩 소켓을 "BTPROTO_RFCOMM"로 지정
   할 때 임의의(any) 주소를 나타내는 데 사용할 수 있습니다.

socket.BDADDR_BREDR
socket.BDADDR_LE_PUBLIC
socket.BDADDR_LE_RANDOM

   These constants describe the Bluetooth address type when binding or
   connecting a "BTPROTO_L2CAP" socket.

   가용성: Linux, FreeBSD

   Added in version 3.14.

socket.SOL_RFCOMM
socket.SOL_L2CAP
socket.SOL_HCI
socket.SOL_SCO
socket.SOL_BLUETOOTH

   Used in the level argument to the "setsockopt()" and "getsockopt()"
   methods of Bluetooth socket objects.

   "SOL_BLUETOOTH" is only available on Linux. Other constants are
   available if the corresponding protocol is supported.

SO_L2CAP_*
socket.L2CAP_LM
L2CAP_LM_*
SO_RFCOMM_*
RFCOMM_LM_*
SO_SCO_*
SO_BTH_*
BT_*

   Used in the option name and value argument to the "setsockopt()"
   and "getsockopt()" methods of Bluetooth socket objects.

   "BT_*" and "L2CAP_LM" are only available on Linux. "SO_BTH_*" are
   only available on Windows. Other constants may be available on
   Linux and various BSD platforms.

   Added in version 3.14.

socket.HCI_FILTER
socket.HCI_TIME_STAMP
socket.HCI_DATA_DIR
socket.SO_HCI_EVT_FILTER
socket.SO_HCI_PKT_FILTER

   Option names for use with "BTPROTO_HCI". Availability and format of
   the option values depend on platform.

   버전 3.14에서 변경: Added "SO_HCI_EVT_FILTER" and
   "SO_HCI_PKT_FILTER" on NetBSD and DragonFly BSD. Added
   "HCI_DATA_DIR" on FreeBSD, NetBSD and DragonFly BSD.

socket.HCI_DEV_NONE

   The "device_id" value used to create an HCI socket that isn't
   specific to a single Bluetooth adapter.

   가용성: Linux

   Added in version 3.14.

socket.HCI_CHANNEL_RAW
socket.HCI_CHANNEL_USER
socket.HCI_CHANNEL_MONITOR
socket.HCI_CHANNEL_CONTROL
socket.HCI_CHANNEL_LOGGING

   Possible values for "channel" field in the "BTPROTO_HCI" address.

   가용성: Linux

   Added in version 3.14.

socket.AF_QIPCRTR

   원격 프로세서를 제공하는 서비스와 통신하는 데 사용되는 Qualcomm의
   IPC 라우터 프로토콜용 상수.

   가용성: Linux >= 4.7.

socket.SCM_CREDS2
socket.LOCAL_CREDS
socket.LOCAL_CREDS_PERSISTENT

   LOCAL_CREDS and LOCAL_CREDS_PERSISTENT can be used with SOCK_DGRAM,
   SOCK_STREAM sockets, equivalent to Linux/DragonFlyBSD SO_PASSCRED,
   while LOCAL_CREDS sends the credentials at first read,
   LOCAL_CREDS_PERSISTENT sends for each read, SCM_CREDS2 must be then
   used for the latter for the message type.

   Added in version 3.11.

   가용성: FreeBSD.

socket.SO_INCOMING_CPU

   Constant to optimize CPU locality, to be used in conjunction with
   "SO_REUSEPORT".

   Added in version 3.11.

   가용성: Linux >= 3.9

socket.SO_REUSEPORT_LB

      Constant to enable duplicate address and port bindings with load
      balancing.

   Added in version 3.14.

   가용성: FreeBSD >= 12.0

socket.AF_HYPERV
socket.HV_PROTOCOL_RAW
socket.HVSOCKET_CONNECT_TIMEOUT
socket.HVSOCKET_CONNECT_TIMEOUT_MAX
socket.HVSOCKET_CONNECTED_SUSPEND
socket.HVSOCKET_ADDRESS_FLAG_PASSTHRU
socket.HV_GUID_ZERO
socket.HV_GUID_WILDCARD
socket.HV_GUID_BROADCAST
socket.HV_GUID_CHILDREN
socket.HV_GUID_LOOPBACK
socket.HV_GUID_PARENT

   Constants for Windows Hyper-V sockets for host/guest
   communications.

   가용성: Windows.

   Added in version 3.12.

socket.ETHERTYPE_ARP
socket.ETHERTYPE_IP
socket.ETHERTYPE_IPV6
socket.ETHERTYPE_VLAN

   IEEE 802.3 protocol number. constants.

   가용성: Linux, FreeBSD, macOS.

   Added in version 3.12.

socket.SHUT_RD
socket.SHUT_WR
socket.SHUT_RDWR

   These constants are used by the "shutdown()" method of socket
   objects.

   가용성: not WASI.


함수
----


소켓 만들기
~~~~~~~~~~~

다음 함수는 모두 소켓 객체를 만듭니다.

class socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)

   지정된 주소 패밀리, 소켓 유형, 및 프로토콜 번호를 사용하여 새로운
   소켓을 만듭니다. 주소 패밀리는 "AF_INET" (기본값), "AF_INET6",
   "AF_UNIX", "AF_CAN", "AF_PACKET" 또는 "AF_RDS" 여야 합니다. 소켓 유
   형은 "SOCK_STREAM" (기본값), "SOCK_DGRAM", "SOCK_RAW" 또는 기타
   "SOCK_" 상수 중 하나여야 합니다. 프로토콜 번호는 일반적으로 0이며
   생략될 수도 있고, 주소 패밀리가 "AF_CAN" 일 때 프로토콜은
   "CAN_RAW", "CAN_BCM", "CAN_ISOTP" 또는 "CAN_J1939" 중 하나여야 합니
   다.

   If *fileno* is specified, the values for *family*, *type*, and
   *proto* are auto-detected from the specified file descriptor.
   Auto-detection can be overruled by calling the function with
   explicit *family*, *type*, or *proto* arguments.  This only affects
   how Python represents e.g. the return value of
   "socket.getpeername()" but not the actual OS resource.  Unlike
   "socket.fromfd()", *fileno* will return the same socket and not a
   duplicate. This may help close a detached socket using
   "socket.close()".

   새로 만들어진 소켓은 상속 불가능합니다.

   "self", "family", "type", "protocol"를 인자로 감사 이벤트(auditing
   event) "socket.__new__"를 발생시킵니다.

   버전 3.3에서 변경: AF_CAN 패밀리가 추가되었습니다. AF_RDS 패밀리가
   추가되었습니다.

   버전 3.4에서 변경: CAN_BCM 프로토콜이 추가되었습니다.

   버전 3.4에서 변경: 반환된 소켓은 이제 상속 불가능합니다.

   버전 3.7에서 변경: CAN_ISOTP 프로토콜이 추가되었습니다.

   버전 3.7에서 변경: When "SOCK_NONBLOCK" or "SOCK_CLOEXEC" bit flags
   are applied to *type* they are cleared, and "socket.type" will not
   reflect them.  They are still passed to the underlying system
   "socket()" call.  Therefore,

      sock = socket.socket(
          socket.AF_INET,
          socket.SOCK_STREAM | socket.SOCK_NONBLOCK)

   는 여전히 "SOCK_NONBLOCK"를 지원하는 OS에서 비 블로킹 소켓을 만들지
   만, "sock.type"은 "socket.SOCK_STREAM"로 설정됩니다.

   버전 3.9에서 변경: CAN_J1939 프로토콜이 추가되었습니다.

   버전 3.10에서 변경: The IPPROTO_MPTCP protocol was added.

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".

   새로 만들어진 소켓은 상속 불가능합니다.

   버전 3.2에서 변경: 반환된 소켓 객체는 이제 부분 집합이 아닌 전체 소
   켓 API를 지원합니다.

   버전 3.4에서 변경: 반환된 소켓은 이제 상속 불가능합니다.

   버전 3.5에서 변경: 윈도우 지원이 추가되었습니다.

socket.create_connection(address, timeout=GLOBAL_DEFAULT, source_address=None, *, all_errors=False)

   Connect to a TCP service listening on the internet *address* (a
   2-tuple "(host, port)"), and return the socket object.  This is a
   higher-level function than "socket.connect()": if *host* is a non-
   numeric hostname, it will try to resolve it for both "AF_INET" and
   "AF_INET6", and then try to connect to all possible addresses in
   turn until a connection succeeds.  This makes it easy to write
   clients that are compatible to both IPv4 and IPv6.

   선택적 *timeout* 매개 변수를 전달하면 연결을 시도하기 전에 소켓 인
   스턴스의 시간제한을 설정합니다. *timeout*이 제공되지 않으면,
   "getdefaulttimeout()"에 의해 반환된 전역 기본 시간제한 설정이 사용
   됩니다.

   제공되면, *source_address*는 연결하기 전에 소켓이 소스 주소로 바인
   드 할 2-튜플 "(host, port)" 여야 합니다. 호스트나 포트가 각각 '' 나
   0이면 OS 기본 동작이 사용됩니다.

   When a connection cannot be created, an exception is raised. By
   default, it is the exception from the last address in the list. If
   *all_errors* is "True", it is an "ExceptionGroup" containing the
   errors of all attempts.

   버전 3.2에서 변경: *source_address*가 추가되었습니다.

   버전 3.11에서 변경: *all_errors* was added.

socket.create_server(address, *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False)

   Convenience function which creates a TCP socket bound to *address*
   (a 2-tuple "(host, port)") and returns the socket object.

   *family* should be either "AF_INET" or "AF_INET6". *backlog* is the
   queue size passed to "socket.listen()"; if not specified , a
   default reasonable value is chosen. *reuse_port* dictates whether
   to set the "SO_REUSEPORT" socket option.

   If *dualstack_ipv6* is true, *family* is "AF_INET6" and the
   platform supports it the socket will be able to accept both IPv4
   and IPv6 connections, else it will raise "ValueError". Most POSIX
   platforms and Windows are supposed to support this functionality.
   When this functionality is enabled the address returned by
   "socket.getpeername()" when an IPv4 connection occurs will be an
   IPv6 address represented as an IPv4-mapped IPv6 address. If
   *dualstack_ipv6* is false it will explicitly disable this
   functionality on platforms that enable it by default (e.g. Linux).
   This parameter can be used in conjunction with
   "has_dualstack_ipv6()":

      import socket

      addr = ("", 8080)  # all interfaces, port 8080
      if socket.has_dualstack_ipv6():
          s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True)
      else:
          s = socket.create_server(addr)

   참고:

     POSIX 플랫폼에서 "SO_REUSEADDR" 소켓 옵션은 같은 *address*에 바인
     드 되었고 TIME_WAIT 상태로 남아 있던 이전 소켓을 즉시 재사용하기
     위해 설정됩니다.

   Added in version 3.8.

socket.has_dualstack_ipv6()

   플랫폼이 IPv4와 IPv6 연결을 모두 처리할 수 있는 TCP 소켓을 만드는
   것을 지원하면 "True"를 반환합니다.

   Added in version 3.8.

socket.fromfd(fd, family, type, proto=0)

   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.

   새로 만들어진 소켓은 상속 불가능합니다.

   버전 3.4에서 변경: 반환된 소켓은 이제 상속 불가능합니다.

socket.fromshare(data)

   "socket.share()" 메서드에서 얻은 데이터로 소켓의 인스턴스를 만듭니
   다. 소켓은 블로킹 모드로 간주합니다.

   가용성: Windows.

   Added in version 3.3.

socket.SocketType

   이것은 소켓 객체 형을 나타내는 파이썬 형 객체입니다.
   "type(socket(...))"과 같습니다.


기타 함수
~~~~~~~~~

"socket" 모듈은 또한 다양한 네트워크 관련 서비스를 제공합니다:

socket.close(fd)

   소켓 파일 기술자를 닫습니다. 이것은 "os.close()"와 비슷하지만, 소켓
   용입니다. 일부 플랫폼(가장 눈에 띄는 것은 윈도우)에서는
   "os.close()"가 소켓 파일 기술자에 대해 작동하지 않습니다.

   Added in version 3.7.

socket.getaddrinfo(host, port, family=AF_UNSPEC, type=0, proto=0, flags=0)

   This function wraps the C function "getaddrinfo" of the underlying
   system.

   *host*/*port* 인자를 해당 서비스에 연결된 소켓을 만드는 데 필요한
   모든 인자가 들어있는 5-튜플의 시퀀스로 변환합니다. *host*는 도메인
   이름, IPv4/v6 주소의 문자열 표현 또는 "None"입니다. *port*는
   "'http'"와 같은 문자열 서비스 이름, 숫자 포트 번호 또는 "None"입니
   다. "None"을 *host* 와 *port*의 값으로 전달해서, "NULL"을 하부 C
   API에 전달할 수 있습니다.

   The *family*, *type* and *proto* arguments can be optionally
   specified in order to provide options and limit the list of
   addresses returned. Pass their default values ("AF_UNSPEC", 0, and
   0, respectively) to not limit the results. See the note below for
   details.

   The *flags* argument can be one or several of the "AI_*" constants,
   and will influence how results are computed and returned. For
   example, "AI_NUMERICHOST" will disable domain name resolution and
   will raise an error if *host* is a domain name.

   이 함수는 다음과 같은 구조의 5-튜플의 리스트를 반환합니다:

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

   In these tuples, *family*, *type*, *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, flowinfo, scope_id)"
   4-tuple for "AF_INET6"), and is meant to be passed to the
   "socket.connect()" method.

   참고:

     If you intend to use results from "getaddrinfo()" to create a
     socket (rather than, for example, retrieve *canonname*), consider
     limiting the results by *type* (e.g. "SOCK_STREAM" or
     "SOCK_DGRAM") and/or *proto* (e.g. "IPPROTO_TCP" or
     "IPPROTO_UDP") that your application can handle.The behavior with
     default values of *family*, *type*, *proto* and *flags* is
     system-specific.Many systems (for example, most Linux
     configurations) will return a sorted list of all matching
     addresses. These addresses should generally be tried in order
     until a connection succeeds (possibly tried in parallel, for
     example, using a Happy Eyeballs algorithm). In these cases,
     limiting the *type* and/or *proto* can help eliminate
     unsuccessful or unusable connection attempts.Some systems will,
     however, only return a single address. (For example, this was
     reported on Solaris and AIX configurations.) On these systems,
     limiting the *type* and/or *proto* helps ensure that this address
     is usable.

   "host", "port", "family", "type", "protocol"을 인자로 감사 이벤트
   (auditing event) "socket.getaddrinfo"를 발생시킵니다.

   다음 예제는 "example.org"의 포트 80으로 가는 가상의 TCP 연결에 대한
   주소 정보를 가져옵니다 (IPv6가 활성화되지 않았으면 여러분의 시스템
   에서는 결과가 다를 수 있습니다):

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

   버전 3.2에서 변경: 매개 변수는 이제 키워드 인자를 사용하여 전달할
   수 있습니다.

   버전 3.7에서 변경: IPv6 멀티캐스트 주소의 경우, 주소를 나타내는 문
   자열에는 "%scope_id" 부분이 포함되지 않습니다.

socket.getfqdn([name])

   Return a fully qualified domain name for *name*. If *name* is
   omitted or empty, it is interpreted as the local host.  To find the
   fully qualified name, the hostname returned by "gethostbyaddr()" is
   checked, followed by aliases for the host, if available.  The first
   name which includes a period is selected.  In case no fully
   qualified domain name is available and *name* was provided, it is
   returned unchanged.  If *name* was empty or equal to "'0.0.0.0'",
   the hostname from "gethostname()" is returned.

socket.gethostbyname(hostname)

   호스트 이름을 IPv4 주소 형식으로 변환합니다. IPv4 주소는
   "'100.50.200.5'"와 같은 문자열로 반환됩니다. 호스트 이름이 IPv4 주
   소면 변경되지 않고 반환됩니다. 더욱 완전한 인터페이스는
   "gethostbyname_ex()"를 참조하십시오. "gethostbyname()"는 IPv6 이름
   결정을 지원하지 않으며, IPv4/v6 이중 스택 지원을 위해서는 대신
   "getaddrinfo()"를 사용해야 합니다.

   "hostname"을 인자로 감사 이벤트(auditing event)
   "socket.gethostbyname"을 발생시킵니다.

   가용성: not WASI.

socket.gethostbyname_ex(hostname)

   Translate a host name to IPv4 address format, extended interface.
   Return a 3-tuple "(hostname, aliaslist, ipaddrlist)" where
   *hostname* is the host's primary host name, *aliaslist* is a
   (possibly empty) list of alternative host names for the same
   address, and *ipaddrlist* is a list of IPv4 addresses for the same
   interface on the same host (often but not always a single address).
   "gethostbyname_ex()" does not support IPv6 name resolution, and
   "getaddrinfo()" should be used instead for IPv4/v6 dual stack
   support.

   "hostname"을 인자로 감사 이벤트(auditing event)
   "socket.gethostbyname"을 발생시킵니다.

   가용성: not WASI.

socket.gethostname()

   파이썬 인터프리터가 현재 실행 중인 기계의 호스트 명을 포함한 문자열
   을 반환합니다.

   인자 없이 감사 이벤트(auditing event) "socket.gethostname"을 발생시
   킵니다.

   참고: "gethostname()"은 항상 완전히 정규화된 도메인 이름을 반환하지
   는 않습니다; 원한다면 "getfqdn()"을 사용하십시오.

   가용성: not WASI.

socket.gethostbyaddr(ip_address)

   Return a 3-tuple "(hostname, aliaslist, ipaddrlist)" where
   *hostname* is the primary host name responding to the given
   *ip_address*, *aliaslist* is a (possibly empty) list of alternative
   host names for the same address, and *ipaddrlist* is a list of
   IPv4/v6 addresses for the same interface on the same host (most
   likely containing only a single address). To find the fully
   qualified domain name, use the function "getfqdn()".
   "gethostbyaddr()" supports both IPv4 and IPv6.

   "ip_address"를 인자로 감사 이벤트(auditing event)
   "socket.gethostbyaddr"을 발생시킵니다.

   가용성: not WASI.

socket.getnameinfo(sockaddr, flags)

   Translate a socket address *sockaddr* into a 2-tuple "(host,
   port)". Depending on the settings of *flags*, the result can
   contain a fully qualified domain name or numeric address
   representation in *host*.  Similarly, *port* can contain a string
   port name or a numeric port number.

   IPv6 주소의 경우, *sockaddr*에 의미 있는 *scope_id*가 있으면
   "%scope_id"를 host 부분에 덧붙입니다. 보통 이것은 멀티캐스트 주소에
   서 일어납니다.

   *flags*에 대한 자세한 내용은 *getnameinfo(3)*을 참조하십시오.

   "sockaddr"을 인자로 감사 이벤트(auditing event)
   "socket.getnameinfo"를 발생시킵니다.

   가용성: not WASI.

socket.getprotobyname(protocolname)

   Translate an internet protocol name (for example, "'icmp'") to a
   constant suitable for passing as the (optional) third argument to
   the "socket()" function.  This is usually only needed for sockets
   opened in "raw" mode ("SOCK_RAW"); for the normal socket modes, the
   correct protocol is chosen automatically if the protocol is omitted
   or zero.

   가용성: not WASI.

socket.getservbyname(servicename[, protocolname])

   Translate an internet service name and protocol name to a port
   number for that service.  The optional protocol name, if given,
   should be "'tcp'" or "'udp'", otherwise any protocol will match.

   "servicename", "protocolname"을 인자로 감사 이벤트(auditing event)
   "socket.getservbyname"을 발생시킵니다.

   가용성: not WASI.

socket.getservbyport(port[, protocolname])

   Translate an internet port number and protocol name to a service
   name for that service.  The optional protocol name, if given,
   should be "'tcp'" or "'udp'", otherwise any protocol will match.

   "port", "protocolname"을 인자로 감사 이벤트(auditing event)
   "socket.getservbyport"를 발생시킵니다.

   가용성: not WASI.

socket.ntohl(x)

   32비트 양의 정수를 네트워크 바이트 순서에서 호스트 바이트 순서로 변
   환합니다. 호스트 바이트 순서가 네트워크 바이트 순서와 같은 시스템에
   서, 이것은 아무 일도 하지 않습니다; 그렇지 않으면, 4바이트 스와프
   연산을 수행합니다.

socket.ntohs(x)

   16비트 양의 정수를 네트워크 바이트 순서에서 호스트 바이트 순서로 변
   환합니다. 호스트 바이트 순서가 네트워크 바이트 순서와 같은 시스템에
   서, 이것은 아무 일도 하지 않습니다; 그렇지 않으면, 2바이트 스와프
   연산을 수행합니다.

   버전 3.10에서 변경: Raises "OverflowError" if *x* does not fit in a
   16-bit unsigned integer.

socket.htonl(x)

   32비트 양의 정수를 호스트 바이트 순서에서 네트워크 바이트 순서로 변
   환합니다. 호스트 바이트 순서가 네트워크 바이트 순서와 같은 시스템에
   서, 이것은 아무 일도 하지 않습니다; 그렇지 않으면, 4바이트 스와프
   연산을 수행합니다.

socket.htons(x)

   16비트 양의 정수를 호스트 바이트 순서에서 네트워크 바이트 순서로 변
   환합니다. 호스트 바이트 순서가 네트워크 바이트 순서와 같은 시스템에
   서, 이것은 아무 일도 하지 않습니다; 그렇지 않으면, 2바이트 스와프
   연산을 수행합니다.

   버전 3.10에서 변경: Raises "OverflowError" if *x* does not fit in a
   16-bit unsigned integer.

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 bytes
   object four characters in length.  This is useful when conversing
   with a program that uses the standard C library and needs objects
   of type "in_addr", which is the C type for the 32-bit packed binary
   this function returns.

   "inet_aton()"는 3점 미만의 문자열도 허용합니다; 자세한 내용은 유닉
   스 매뉴얼 페이지 *inet(3)*을 참조하십시오.

   이 함수에 전달된 IPv4 주소 문자열이 유효하지 않으면, "OSError"가 발
   생합니다. 정확히 무엇이 유효한지는 "inet_aton()"의 하부 C 구현에 따
   라 달라짐에 유의하십시오.

   "inet_aton()"은 IPv6를 지원하지 않으며, IPv4/v6 이중 스택 지원을 위
   해서는 대신 "inet_pton()"를 사용해야 합니다.

socket.inet_ntoa(packed_ip)

   Convert a 32-bit packed IPv4 address (a *bytes-like object* four
   bytes 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 "in_addr", which is the C type for the 32-bit packed binary
   data this function takes as an argument.

   이 함수에 전달된 바이트 시퀀스가 정확히 4바이트 길이가 아니면,
   "OSError"가 발생합니다. "inet_ntoa()"는 IPv6를 지원하지 않으며,
   IPv4/v6 이중 스택 지원을 위해서는 대신 "inet_ntop()"를 사용해야 합
   니다.

   버전 3.5에서 변경: 이제 쓰기 가능한 *바이트열류 객체*를 받아들입니
   다.

socket.inet_pton(address_family, ip_string)

   Convert an IP address from its family-specific string format to a
   packed, binary format. "inet_pton()" is useful when a library or
   network protocol calls for an object of type "in_addr" (similar to
   "inet_aton()") or "in6_addr".

   *address_family*에 대해 지원되는 값은 현재 "AF_INET"과 "AF_INET6"입
   니다. IP 주소 문자열 *ip_string*가 유효하지 않으면, "OSError"가 발
   생합니다. 정확히 무엇이 유효한지는 *address_family*의 값과
   "inet_pton()"의 하부 구현에 따라 달라집니다.

   가용성: Unix, Windows.

   버전 3.4에서 변경: 윈도우 지원이 추가되었습니다

socket.inet_ntop(address_family, packed_ip)

   Convert a packed IP address (a *bytes-like object* of some number
   of bytes) 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
   "in_addr" (similar to "inet_ntoa()") or "in6_addr".

   *address_family*에 대해 지원되는 값은 현재 "AF_INET"과 "AF_INET6"입
   니다. 바이트열 객체 *packed_ip*가 지정된 주소 패밀리의 올바른 길이
   가 아니면, "ValueError"가 발생합니다. "inet_ntop()" 호출로 인한 에
   러에는 "OSError"가 발생합니다.

   가용성: Unix, Windows.

   버전 3.4에서 변경: 윈도우 지원이 추가되었습니다

   버전 3.5에서 변경: 이제 쓰기 가능한 *바이트열류 객체*를 받아들입니
   다.

socket.CMSG_LEN(length)

   주어진 *length*의 연관된 데이터가 있는 보조(ancillary) 데이터 항목
   의 (후행 패딩을 제외한) 총 길이를 반환합니다. 이 값은 "recvmsg()"가
   보조 데이터의 단일 항목을 수신하기 위한 버퍼 크기로 종종 사용될 수
   있지만, **RFC 3542**는 이식성 있는 응용 프로그램에서 "CMSG_SPACE()"
   를 사용하도록 요구하는데, 항목이 버퍼의 마지막 부분일 때도 패딩을
   위한 공간을 포함합니다. *length*가 허용되는 값 범위를 벗어나면
   "OverflowError"를 발생시킵니다.

   가용성: Unix, not WASI.

   Most Unix platforms.

   Added in version 3.3.

socket.CMSG_SPACE(length)

   주어진 *length*의 연관된 데이터가 있는 보조(ancillary) 데이터 항목
   을 수신하기 위해 "recvmsg()"에 필요한 버퍼 크기를 반환하는데, 후행
   패딩을 포함합니다. 여러 항목을 수신하는 데 필요한 버퍼 공간은 연관
   된 데이터 길이에 대한 "CMSG_SPACE()" 값의 합입니다. *length*가 허용
   되는 값 범위를 벗어나면 "OverflowError"를 발생시킵니다.

   일부 시스템에서는 이 함수를 제공하지 않으면서 보조(ancillary) 데이
   터를 지원할 수 있음에 유의하십시오. 또한, 이 함수의 결과를 사용하여
   버퍼 크기를 설정하면 수신할 수 있는 보조 데이터의 양이 정확하게 제
   한되지 않을 수 있음에도 유의하십시오. 추가 데이터가 패딩 영역에 들
   어갈 수 있기 때문입니다.

   가용성: Unix, not WASI.

   most Unix platforms.

   Added in version 3.3.

socket.getdefaulttimeout()

   새로운 소켓 객체의 기본 시간제한을 초 단위로 (float) 반환합니다.
   "None" 값은 새 소켓 객체가 시간제한이 없음을 나타냅니다. 소켓 모듈
   을 처음 임포트 할 때 기본값은 "None"입니다.

socket.setdefaulttimeout(timeout)

   새 소켓 객체의 기본 시간제한을 초 단위로 (float) 설정합니다. 소켓
   모듈을 처음 임포트 할 때 기본값은 "None"입니다. 가능한 값과 해당 의
   미는 "settimeout()"을 참조하십시오.

socket.sethostname(name)

   기계의 호스트 명을 *name*으로 설정합니다. 충분한 권한이 없으면
   "OSError"가 발생합니다.

   "name"을 인자로 감사 이벤트(auditing event) "socket.sethostname"을
   발생시킵니다.

   가용성: Unix, not Android.

   Added in version 3.3.

socket.if_nameindex()

   네트워크 인터페이스 정보 (인덱스 정수, 이름 문자열) 튜플의 리스트를
   반환합니다. 시스템 호출이 실패하면 "OSError".

   가용성: Unix, Windows, not WASI.

   Added in version 3.3.

   버전 3.8에서 변경: 윈도우 지원이 추가되었습니다.

   참고:

     윈도우에서 네트워크 인터페이스는 다른 문맥에서 다른 이름을 갖습니
     다 (모든 이름은 예입니다):

     * UUID: "{FB605B73-AAC2-49A6-9A2F-25416AEA0573}"

     * 이름: "ethernet_32770"

     * 친숙한 이름: "vEthernet (nat)"

     * 설명: "Hyper-V Virtual Ethernet Adapter"

     이 함수는 목록에서 두 번째 형식의 이름을 반환합니다, 이 예의 경우
     "ethernet_32770".

socket.if_nametoindex(if_name)

   인터페이스 이름에 대응하는 네트워크 인터페이스 인덱스 번호를 반환합
   니다. 주어진 이름을 가진 인터페이스가 없으면 "OSError".

   가용성: Unix, Windows, not WASI.

   Added in version 3.3.

   버전 3.8에서 변경: 윈도우 지원이 추가되었습니다.

   더 보기: "인터페이스 이름"은 "if_nameindex()"에 설명된 이름입니다.

socket.if_indextoname(if_index)

   인터페이스 인덱스 번호에 해당하는 네트워크 인터페이스 이름을 반환합
   니다. 지정된 인덱스의 인터페이스가 없으면 "OSError".

   가용성: Unix, Windows, not WASI.

   Added in version 3.3.

   버전 3.8에서 변경: 윈도우 지원이 추가되었습니다.

   더 보기: "인터페이스 이름"은 "if_nameindex()"에 설명된 이름입니다.

socket.send_fds(sock, buffers, fds[, flags[, address]])

   Send the list of file descriptors *fds* over an "AF_UNIX" socket
   *sock*. The *fds* parameter is a sequence of file descriptors.
   Consult "sendmsg()" for the documentation of these parameters.

   가용성: Unix, not WASI.

   Unix platforms supporting "sendmsg()" and "SCM_RIGHTS" mechanism.

   Added in version 3.9.

socket.recv_fds(sock, bufsize, maxfds[, flags])

   Receive up to *maxfds* file descriptors from an "AF_UNIX" socket
   *sock*. Return "(msg, list(fds), flags, addr)". Consult "recvmsg()"
   for the documentation of these parameters.

   가용성: Unix, not WASI.

   Unix platforms supporting "recvmsg()" and "SCM_RIGHTS" mechanism.

   Added in version 3.9.

   참고:

     파일 기술자 리스트 끝에 있는 모든 잘린 정수.


소켓 객체
=========

소켓 객체에는 다음과 같은 메서드가 있습니다. "makefile()"를 제외하고,
이것들은 소켓에 적용할 수 있는 유닉스 시스템 호출에 해당합니다.

버전 3.2에서 변경: *컨텍스트 관리자* 프로토콜 지원이 추가되었습니다.
컨텍스트 관리자를 빠져나가는 것은 "close()"를 호출하는 것과 동등합니다
.

socket.accept()

   연결을 받아들입니다. 소켓은 주소에 바인드되어 연결을 리스닝하고 있
   어야 합니다. 반환 값은 "(conn, address)" 쌍입니다. 여기서 *conn*는
   연결에서 데이터를 보내고 받을 수 있는 *새로운* 소켓 객체이고,
   *address*는 연결의 다른 끝에 있는 소켓에 바인드 된 주소입니다.

   새로 만들어진 소켓은 상속 불가능합니다.

   버전 3.4에서 변경: 소켓은 이제 상속 불가능합니다.

   버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외
   를 발생시키지 않으면, 메서드는 이제 "InterruptedError" 예외를 발생
   시키는 대신 시스템 호출을 재시도합니다 (이유는 **PEP 475**를 참조하
   십시오).

socket.bind(address)

   소켓을 *address*에 바인드 합니다. 소켓은 이미 바인드 되어 있으면 안
   됩니다. (*address*의 형식은 주소 패밀리에 따라 다릅니다 --- 위를 보
   십시오.)

   "self", "address"을 인자로 감사 이벤트(auditing event)
   "socket.bind"를 발생시킵니다.

   가용성: not WASI.

socket.close()

   Mark the socket closed.  The underlying system resource (e.g. a
   file descriptor) is also closed when all file objects from
   "makefile()" are closed.  Once that happens, all future operations
   on the socket object will fail. The remote end will receive no more
   data (after queued data is flushed).

   소켓은 가비지 수집될 때 자동으로 닫히지만, 명시적으로 "close()"하거
   나 "with" 문을 사용하는 것이 좋습니다.

   버전 3.6에서 변경: 하부 "close()" 호출이 수행될 때 에러가 발생하면
   이제 "OSError"가 발생합니다.

   참고:

     "close()" releases the resource associated with a connection but
     does not necessarily close the connection immediately.  If you
     want to close the connection in a timely fashion, call
     "shutdown()" before "close()".

socket.connect(address)

   *address*에 있는 원격 소켓에 연결합니다. (*address*의 형식은 주소
   패밀리에 따라 다릅니다 --- 위를 보십시오.)

   If the connection is interrupted by a signal, the method waits
   until the connection completes, or raise a "TimeoutError" on
   timeout, if the signal handler doesn't raise an exception and the
   socket is blocking or has a timeout. For non-blocking sockets, the
   method raises an "InterruptedError" exception if the connection is
   interrupted by a signal (or the exception raised by the signal
   handler).

   "self", "address"를 인자로 감사 이벤트(auditing event)
   "socket.connect"를 발생시킵니다.

   버전 3.5에서 변경: 연결이 시그널에 의해 인터럽트 되고, 시그널 처리
   기가 예외를 발생시키지 않고, 소켓이 블로킹하거나 시간제한을 가지면,
   이 메서드는 이제 "InterruptedError" 예외를 발생시키는 대신 연결이
   완료될 때까지 대기합니다 (이유는 **PEP 475**를 참조하십시오).

   가용성: not WASI.

socket.connect_ex(address)

   "connect(address)"와 비슷하지만, C 수준의 "connect()" 호출로 반환된
   에러에 대한 예외를 발생시키는 대신 에러 표시기를 반환합니다 ("호스
   트를 찾을 수 없음"과 같은 다른 문제는 여전히 예외를 발생시킬 수 있
   습니다). 연산이 성공하면 에러 표시기는 "0"이고, 그렇지 않으면
   "errno" 변수의 값입니다. 예를 들어 비동기 연결을 지원하는 데 유용합
   니다.

   "self", "address"를 인자로 감사 이벤트(auditing event)
   "socket.connect"를 발생시킵니다.

   가용성: not WASI.

socket.detach()

   하부 파일 기술자를 실제로 닫지 않으면서 소켓 객체를 닫힌 상태로 만
   듭니다. 파일 기술자가 반환되고, 다른 용도로 재사용 될 수 있습니다.

   Added in version 3.2.

socket.dup()

   소켓을 복제합니다.

   새로 만들어진 소켓은 상속 불가능합니다.

   버전 3.4에서 변경: 소켓은 이제 상속 불가능합니다.

   가용성: not WASI.

socket.fileno()

   소켓의 파일 기술자(작은 정수)를 반환하거나, 실패하면 -1을 반환합니
   다. 이것은 "select.select()"에서 유용합니다.

   윈도우에서, 이 메서드가 돌려주는 작은 정수는 파일 기술자를 사용할
   수 있는 곳(가령 "os.fdopen()")에 사용할 수 없습니다. 유닉스에는 이
   러한 제한이 없습니다.

socket.get_inheritable()

   소켓의 파일 기술자나 소켓 핸들의 상속 가능 플래그를 가져옵니다: 소
   켓이 자식 프로세스에서 상속될 수 있으면 "True", 그렇지 않으면
   "False".

   Added in version 3.4.

socket.getpeername()

   소켓이 연결된 원격 주소를 반환합니다. 이것은 예를 들어, 원격
   IPv4/v6 소켓의 포트 번호를 찾는 데 유용합니다. (반환되는 주소의 형
   식은 주소 패밀리에 따라 다릅니다 --- 위를 보십시오.) 일부 시스템에
   서는 이 함수가 지원되지 않습니다.

socket.getsockname()

   소켓 자신의 주소를 반환합니다. 이것은 예를 들어 IPv4/v6 소켓의 포트
   번호를 찾는 데 유용합니다. (반환되는 주소의 형식은 주소 패밀리에 따
   라 다릅니다 --- 위를 보십시오.)

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
   bytes object.  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 byte strings).

   가용성: not WASI.

socket.getblocking()

   소켓이 블로킹 모드면 "True"를 반환하고, 비 블로킹이면 "False"를 반
   환합니다.

   This is equivalent to checking "socket.gettimeout() != 0".

   Added in version 3.7.

socket.gettimeout()

   소켓 연산에 관련한 시간제한을 초(float)로 돌려줍니다. 시간제한이 설
   정되어 있지 않으면 "None"를 돌려줍니다. 이것은 "setblocking()" 이나
   "settimeout()"에 대한 마지막 호출을 반영합니다.

socket.ioctl(control, option)

   "ioctl()" 메서드는 WSAIoctl 시스템 인터페이스에 대한 제한된 인터페
   이스입니다. 자세한 내용은 Win32 설명서를 참조하십시오.

   다른 플랫폼에서는, 범용 "fcntl.fcntl()" 과 "fcntl.ioctl()" 함수를
   사용할 수 있습니다; 첫 번째 인자로 소켓 객체를 받아들입니다.

   현재 다음 제어 코드만 지원됩니다: "SIO_RCVALL",
   "SIO_KEEPALIVE_VALS" 및 "SIO_LOOPBACK_FAST_PATH".

   가용성: Windows

   버전 3.6에서 변경: "SIO_LOOPBACK_FAST_PATH"가 추가되었습니다.

socket.listen([backlog])

   서버가 연결을 수락하도록 합니다. *backlog*가 지정되면, 0 이상이어야
   합니다 (더 낮으면 0으로 설정됩니다); 새로운 연결을 거부하기 전에 시
   스템이 허락할 수락되지 않은 연결 수를 지정합니다. 지정하지 않으면,
   기본값으로 적당한 값이 선택됩니다.

   가용성: not WASI.

   버전 3.5에서 변경: 이제 *backlog* 매개 변수가 선택적입니다.

socket.makefile(mode='r', buffering=None, *, encoding=None, errors=None, newline=None)

   Return a *file object* associated with the socket.  The exact
   returned type depends on the arguments given to "makefile()".
   These arguments are interpreted the same way as by the built-in
   "open()" function, except the only supported *mode* values are
   "'r'" (default), "'w'", "'b'", or a combination of those.

   소켓은 블로킹 모드 여야 합니다; 시간제한을 가질 수 있지만, 시간 초
   과가 발생하면 파일 객체의 내부 버퍼가 일관성없는 상태로 끝날 수 있
   습니다.

   "makefile()"에 의해 반환된 파일 객체를 닫는 것은, 다른 모든 파일 객
   체가 닫혔고 소켓 객체에서 "socket.close()"가 호출되었지 않은 한 원
   래 소켓을 닫지는 않습니다.

   참고:

     윈도우에서, "makefile()"로 만든 파일류 객체는 파일 기술자가 있는
     파일 객체가 필요한 곳에서는 사용할 수 없습니다, 가령
     "subprocess.Popen()"의 stream 인자.

socket.recv(bufsize[, flags])

   Receive data from the socket.  The return value is a bytes object
   representing the data received.  The maximum amount of data to be
   received at once is specified by *bufsize*. A returned empty bytes
   object indicates that the client has disconnected. See the Unix
   manual page *recv(2)* for the meaning of the optional argument
   *flags*; it defaults to zero.

   버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외
   를 발생시키지 않으면, 메서드는 이제 "InterruptedError" 예외를 발생
   시키는 대신 시스템 호출을 재시도합니다 (이유는 **PEP 475**를 참조하
   십시오).

socket.recvfrom(bufsize[, flags])

   소켓에서 데이터를 수신합니다. 반환 값은 "(bytes, address)" 쌍입니다
   . 여기서 *bytes*는 수신한 데이터를 나타내는 바이트열 객체이고,
   *address*는 데이터를 보내는 소켓의 주소입니다. 선택적 인자 *flags*
   의 의미는 유닉스 매뉴얼 페이지 *recv(2)*를 보십시오; 기본값은 0입니
   다. (*address*의 형식은 주소 패밀리에 따라 다릅니다 --- 위를 보십시
   오.)

   버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외
   를 발생시키지 않으면, 메서드는 이제 "InterruptedError" 예외를 발생
   시키는 대신 시스템 호출을 재시도합니다 (이유는 **PEP 475**를 참조하
   십시오).

   버전 3.7에서 변경: 멀티캐스트 IPv6 주소의 경우, *address*의 첫 번째
   항목에는 "%scope_id" 부분이 더는 포함되지 않습니다. 전체 IPv6 주소
   를 얻으려면 "getnameinfo()"를 사용하십시오.

socket.recvmsg(bufsize[, ancbufsize[, flags]])

   일반 데이터(최대 *bufsize* 바이트)와 보조(ancillary) 데이터를 소켓
   에서 수신합니다. *ancbufsize* 인자는 보조 데이터 수신에 사용되는 내
   부 버퍼의 크기를 바이트 단위로 설정합니다; 기본값은 0이며 보조 데이
   터가 수신되지 않는다는 뜻입니다. 보조 데이터를 위한 적절한 버퍼 크
   기는 "CMSG_SPACE()" 나 "CMSG_LEN()"를 사용하여 계산할 수 있으며, 버
   퍼에 들어가지 않는 항목은 잘리거나 삭제될 수 있습니다. *flags* 인자
   의 기본값은 0이고 "recv()"와 같은 의미입니다.

   반환 값은 4-튜플입니다: "(data, ancdata, msg_flags, address)".
   *data* 항목은 일반 데이터를 담은 "bytes" 객체입니다. *ancdata* 항목
   은 수신된 보조 데이터(제어 메시지)를 나타내는 0개 이상의 튜플
   "(cmsg_level, cmsg_type, cmsg_data)"의 리스트입니다: *cmsg_level*
   와 *cmsg_type*는 각각 프로토콜 수준과 프로토콜 특정 형을 지정하는
   정수이고, *cmsg_data*는 연결된 데이터를 담은 "bytes" 객체입니다.
   *msg_flags* 항목은 수신된 메시지의 조건을 나타내는 다양한 플래그의
   비트별 OR입니다; 자세한 내용은 시스템 설명서를 참조하십시오. 수신
   소켓이 연결되어있지 않으면, *address*는 송신 소켓의 주소입니다, (사
   용 가능하다면); 그렇지 않으면 값은 지정되지 않습니다.

   On some systems, "sendmsg()" and "recvmsg()" can be used to pass
   file descriptors between processes over an "AF_UNIX" socket.  When
   this facility is used (it is often restricted to "SOCK_STREAM"
   sockets), "recvmsg()" will return, in its ancillary data, items of
   the form "(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)", where *fds*
   is a "bytes" object representing the new file descriptors as a
   binary array of the native C int type.  If "recvmsg()" raises an
   exception after the system call returns, it will first attempt to
   close any file descriptors received via this mechanism.

   일부 시스템은 부분적으로만 수신된 보조 데이터 항목의 절단 길이를 나
   타내지 않습니다. 항목이 버퍼의 끝을 넘어 확장된 것처럼 보이면,
   "recvmsg()"는 "RuntimeWarning"를 발생시키고, 관련 데이터의 시작 전
   에 절단되지 않은 버퍼 내에 있는 부분을 반환합니다.

   "SCM_RIGHTS" 메커니즘을 지원하는 시스템에서, 다음 함수는 최대
   *maxfds* 파일 기술자를 수신하여, 메시지 데이터와 기술자를 담은 리스
   트를 반환합니다 (관련 없는 수신되는 제어 메시지와 같은 예기치 않은
   조건은 무시하면서). "sendmsg()"를 참조하십시오.

      import socket, array

      def recv_fds(sock, msglen, maxfds):
          fds = array.array("i")   # Array of ints
          msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
          for cmsg_level, cmsg_type, cmsg_data in ancdata:
              if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
                  # Append data, ignoring any truncated integers at the end.
                  fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
          return msg, list(fds)

   가용성: Unix.

   Most Unix platforms.

   Added in version 3.3.

   버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외
   를 발생시키지 않으면, 메서드는 이제 "InterruptedError" 예외를 발생
   시키는 대신 시스템 호출을 재시도합니다 (이유는 **PEP 475**를 참조하
   십시오).

socket.recvmsg_into(buffers[, ancbufsize[, flags]])

   "recvmsg()"처럼 동작해서, 일반 데이터와 보조 데이터를 소켓에서 수신
   하지만, 새로운 바이트열 객체를 반환하는 대신 일반 데이터를 일련의
   버퍼로 분산시킵니다. *buffers* 인자는 쓰기 가능한 버퍼(예를 들어,
   "bytearray" 객체)를 내보내는 객체의 이터러블이어야 합니다; 이것들은
   모두 기록되었거나 버퍼가 더는 없을 때까지 일반 데이터의 연속적인 덩
   어리로 채워질 것입니다. 운영 체제는 사용할 수 있는 버퍼 수에 제한
   ("sysconf()" 값 "SC_IOV_MAX")을 설정할 수 있습니다. *ancbufsize* 와
   *flags* 인자는 "recvmsg()"와 같은 의미가 있습니다.

   반환 값은 4-튜플입니다: "(nbytes, ancdata, msg_flags, address)". 여
   기서 *nbytes*는 버퍼에 기록된 일반 데이터의 총 바이트 수이며,
   *ancdata*, *msg_flags* 및 *address*는 "recvmsg()"와 같습니다.

   예제:

      >>> import socket
      >>> s1, s2 = socket.socketpair()
      >>> b1 = bytearray(b'----')
      >>> b2 = bytearray(b'0123456789')
      >>> b3 = bytearray(b'--------------')
      >>> s1.send(b'Mary had a little lamb')
      22
      >>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
      (22, [], 0, None)
      >>> [b1, b2, b3]
      [bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]

   가용성: Unix.

   Most Unix platforms.

   Added in version 3.3.

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

   소켓에서 데이터를 수신하는데, 새로운 바이트열을 만드는 대신
   *buffer*에 씁니다. 반환 값은 쌍 "(nbytes, address)"입니다. 여기서
   *nbytes*는 수신 된 바이트 수이고, *address*는 데이터를 보내는 소켓
   의 주소입니다. 선택적 인자 *flags*의 의미에 대해서는 유닉스 매뉴얼
   페이지 *recv(2)*를 보십시오; 기본값은 0입니다. (*address*의 형식은
   주소 패밀리에 따라 다릅니다 --- 위를 보십시오.)

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

   소켓에서 최대 *nbytes* 바이트까지 수신하는데, 새 바이트열을 만드는
   대신 데이터를 버퍼에 저장합니다. *nbytes*가 지정되지 않으면 (또는
   0), 지정된 버퍼에서 사용 가능한 크기까지 수신합니다. 수신 한 바이트
   수를 반환합니다. 선택적 인자 *flags*의 의미에 대해서는 유닉스 매뉴
   얼 페이지 *recv(2)*를 보십시오; 기본값은 0입니다.

socket.send(bytes[, flags])

   소켓에 데이터를 보냅니다. 소켓은 원격 소켓에 연결되어야 합니다. 선
   택적 *flags* 인자는 위의 "recv()"와 같은 의미입니다. 전송된 바이트
   수를 반환합니다. 응용 프로그램은 모든 데이터가 전송되었는지 확인해
   야 합니다; 일부 데이터만 전송되었으면, 응용 프로그램은 나머지 데이
   터의 전달을 시도해야 합니다. 이 주제에 대한 자세한 정보는, 소켓 프
   로그래밍 HOWTO를 참조하십시오.

   버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외
   를 발생시키지 않으면, 메서드는 이제 "InterruptedError" 예외를 발생
   시키는 대신 시스템 호출을 재시도합니다 (이유는 **PEP 475**를 참조하
   십시오).

socket.sendall(bytes[, flags])

   소켓에 데이터를 보냅니다. 소켓은 원격 소켓에 연결되어야 합니다. 선
   택적 *flags* 인자는 위의 "recv()"와 같은 의미입니다. "send()"와 달
   리, 이 메서드는 모든 데이터가 전송되거나 에러가 발생할 때까지
   *bytes*의 데이터를 계속 전송합니다. 성공하면 "None"이 반환됩니다.
   에러가 발생하면, 예외가 발생하는데, 성공적으로 전송된 데이터양을 (
   있기는 하다면) 확인하는 방법은 없습니다.

   버전 3.5에서 변경: The socket timeout is no longer reset each time
   data is sent successfully. The socket timeout is now the maximum
   total duration to send all data.

   버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외
   를 발생시키지 않으면, 메서드는 이제 "InterruptedError" 예외를 발생
   시키는 대신 시스템 호출을 재시도합니다 (이유는 **PEP 475**를 참조하
   십시오).

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

   소켓에 데이터를 보냅니다. 대상 소켓이 *address*로 지정되므로, 소켓
   은 원격 소켓에 연결되지 않아야 합니다. 선택적 *flags* 인자는 위의
   "recv()"와 같은 의미가 있습니다. 전송된 바이트 수를 반환합니다.
   (*address*의 형식은 주소 패밀리에 따라 다릅니다 --- 위를 보십시오.)

   "self", "address"를 인자로 감사 이벤트(auditing event)
   "socket.sendto"를 발생시킵니다.

   버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외
   를 발생시키지 않으면, 메서드는 이제 "InterruptedError" 예외를 발생
   시키는 대신 시스템 호출을 재시도합니다 (이유는 **PEP 475**를 참조하
   십시오).

socket.sendmsg(buffers[, ancdata[, flags[, address]]])

   소켓에 일반과 보조 데이터를 보는데, 일련의 버퍼에서 일반 데이터를
   모아서 단일 메시지로 연결합니다. *buffers* 인자는 일반 데이터를 *바
   이트열류 객체*의 이터러블로 지정합니다 (예를 들어, "bytes" 객체);
   운영 체제는 사용할 수 있는 버퍼 수에 제한("sysconf()" 값
   "SC_IOV_MAX")을 설정할 수 있습니다. *ancdata* 인자는 보조 데이터 (
   제어 메시지)를 0개 이상의 튜플 "(cmsg_level, cmsg_type, cmsg_data)"
   의 이터러블로 지정합니다. 여기서 *cmsg_level* 와 *cmsg_type*는 각각
   프로토콜 수준과 프로토콜 특정 형을 지정하는 정수이고, *cmsg_data*는
   연결된 데이터를 담은 바이트열류 객체입니다. 일부 시스템(특히,
   "CMSG_SPACE()"가 없는 시스템)은 호출 당 하나의 제어 메시지를 송신하
   는 것만 지원할 수 있습니다. *flags* 인자의 기본값은 0이고 "send()"
   와 같은 의미입니다. *address*가 제공되고 "None"이 아니면, 메시지의
   대상 주소를 설정합니다. 반환 값은 전송된 일반 데이터의 바이트 수입
   니다.

   다음 함수는 "SCM_RIGHTS" 메커니즘을 지원하는 시스템에서, "AF_UNIX"
   소켓을 통해 파일 기술자 리스트 *fds*를 보냅니다. "recvmsg()"도 참조
   하세요.

      import socket, array

      def send_fds(sock, msg, fds):
          return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])

   가용성: Unix, not WASI.

   Most Unix platforms.

   "self", "address"를 인자로 감사 이벤트(auditing event)
   "socket.sendmsg"를 발생시킵니다.

   Added in version 3.3.

   버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외
   를 발생시키지 않으면, 메서드는 이제 "InterruptedError" 예외를 발생
   시키는 대신 시스템 호출을 재시도합니다 (이유는 **PEP 475**를 참조하
   십시오).

socket.sendmsg_afalg([msg, ]*, op[, iv[, assoclen[, flags]]])

   "AF_ALG" 소켓용, "sendmsg()"의 특수한 버전. "AF_ALG" 소켓에 대한 모
   드, IV, AEAD 관련 데이터 길이 및 플래그를 설정합니다.

   가용성: Linux >= 2.6.38.

   Added in version 3.6.

socket.sendfile(file, offset=0, count=None)

   고성능 "os.sendfile"을 사용하여 EOF에 도달할 때까지 파일을 보내고,
   보낸 총 바이트 수를 반환합니다. *file*은 바이너리 모드로 열린 일반
   파일 객체여야 합니다. "os.sendfile"을 사용할 수 없거나 (예를 들어,
   윈도우) *file*가 일반 파일이 아니면, "send()"가 대신 사용됩니다.
   *offset*은 파일 읽기 시작할 위치를 알려줍니다. 지정되면, *count*는
   EOF에 도달할 때까지 파일을 전송하는 대신 전송할 총 바이트 수입니다.
   파일 위치는 반환하거나 에러가 발생했을 때 갱신됩니다. 이때
   "file.tell()"을 사용하여 전송된 바이트 수를 계산할 수 있습니다. 소
   켓은 "SOCK_STREAM" 유형이어야 합니다. 비 블로킹 소켓은 지원되지 않
   습니다.

   Added in version 3.5.

socket.set_inheritable(inheritable)

   소켓의 파일 기술자나 소켓 핸들의 상속 가능 플래그를 설정합니다.

   Added in version 3.4.

socket.setblocking(flag)

   소켓의 블로킹이나 비 블로킹 모드를 설정합니다. *flag*가 거짓이면,
   소켓은 비 블로킹으로 설정되고, 그렇지 않으면 블로킹 모드로 설정됩니
   다.

   이 메서드는 특정 "settimeout()" 호출의 줄인 표현입니다:

   * "sock.setblocking(True)"는 "sock.settimeout(None)"와 동등합니다

   * "sock.setblocking(False)"는 "sock.settimeout(0.0)"와 동등합니다

   버전 3.7에서 변경: 이 메서드는 더는 "socket.type"에 "SOCK_NONBLOCK"
   플래그를 적용하지 않습니다.

socket.settimeout(value)

   Set a timeout on blocking socket operations.  The *value* argument
   can be a nonnegative floating-point number expressing seconds, or
   "None". If a non-zero value is given, subsequent socket operations
   will raise a "timeout" exception if the timeout period *value* has
   elapsed before the operation has completed.  If zero is given, the
   socket is put in non-blocking mode. If "None" is given, the socket
   is put in blocking mode.

   자세한 내용은, 소켓 시간제한에 대한 참고 사항을 보십시오.

   버전 3.7에서 변경: 이 메서드는 더는 "socket.type"의 "SOCK_NONBLOCK"
   플래그를 토글하지 않습니다.

socket.setsockopt(level, optname, value: int)

socket.setsockopt(level, optname, value: buffer)

socket.setsockopt(level, optname, None, optlen: int)

   Set the value of the given socket option (see the Unix manual page
   *setsockopt(2)*).  The needed symbolic constants are defined in
   this module (*SO_* etc. <socket-unix-constants>*).  The value can
   be an integer, "None" or a *bytes-like object* representing a
   buffer. In the later case it is up to the caller to ensure that the
   bytestring contains the proper bits (see the optional built-in
   module "struct" for a way to encode C structures as bytestrings).
   When *value* is set to "None", *optlen* argument is required. It's
   equivalent to call "setsockopt()" C function with "optval=NULL" and
   "optlen=optlen".

   버전 3.5에서 변경: 이제 쓰기 가능한 *바이트열류 객체*를 받아들입니
   다.

   버전 3.6에서 변경: setsockopt(level, optname, None, optlen: int) 형
   식이 추가되었습니다.

   가용성: not WASI.

socket.shutdown(how)

   연결의 한쪽 또는 양쪽 절반을 닫습니다. *how*가 "SHUT_RD"면, 추가 수
   신이 허용되지 않습니다. *how*가 "SHUT_WR"이면, 추가 전송이 허용되지
   않습니다. *how*가 "SHUT_RDWR"이면, 추가 송수신이 허용되지 않습니다.

   가용성: not WASI.

socket.share(process_id)

   소켓을 복제하고 대상 프로세스와 공유할 수 있도록 준비합니다. 대상
   프로세스는 *process_id*로 제공되어야 합니다. 결과 바이트열 객체는
   어떤 프로세스 간 통신의 형태를 사용하여 대상 프로세스로 전달될 수
   있으며 그곳에서 "fromshare()"를 사용하여 소켓을 다시 만들 수 있습니
   다. 일단, 이 메서드가 호출되면, 운영 체제가 이미 대상 프로세스를 위
   해 이를 복제 했으므로 소켓을 닫아도 안전합니다.

   가용성: Windows.

   Added in version 3.3.

메서드 "read()" 나 "write()"가 없다는 점에 유의하십시오; 대신 "recv()"
와 "send()"를 *flags* 인자 없이 사용하십시오.

소켓 객체는 또한 "socket" 생성자에 지정된 값에 대응하는 다음과 같은 (
읽기 전용) 어트리뷰트를 가집니다.

socket.family

   소켓 패밀리.

socket.type

   소켓 유형.

socket.proto

   소켓 프로토콜.


소켓 시간제한에 대한 참고 사항
==============================

소켓 객체는 세 가지 모드 중 하나일 수 있습니다: 블로킹, 비 블로킹, 또
는 시간제한. 소켓은 기본적으로 항상 블로킹 모드로 생성되지만, 이는
"setdefaulttimeout()"를 호출하여 변경할 수 있습니다.

* *블로킹 모드*에서, 연산은 완료되거나 시스템에서 에러(가령 연결 시간
  초과)를 반환할 때까지 블록합니다.

* In *non-blocking mode*, operations fail (with an error that is
  unfortunately system-dependent) if they cannot be completed
  immediately: functions from the "select" module can be used to know
  when and whether a socket is available for reading or writing.

* *시간제한 모드*에서, 연산은 소켓에 대해 지정된 제한 시간 내에 완료할
  수 없거나 ("timeout" 예외 발생), 시스템이 에러를 반환하면 실패합니다
  .

참고:

  At the operating system level, sockets in *timeout mode* are
  internally set in non-blocking mode.  Also, the blocking and timeout
  modes are shared between file descriptors and socket objects that
  refer to the same network endpoint. This implementation detail can
  have visible consequences if e.g. you decide to use the "fileno()"
  of a socket.


시간제한과 "connect" 메서드
---------------------------

"connect()" 연산도 시간제한 설정의 영향을 받으며, 일반적으로
"connect()"를 호출하기 전에 "settimeout()"를 호출하거나
"create_connection()"에 timeout 매개 변수를 전달하는 것이 좋습니다. 그
러나, 시스템 네트워크 스택은 파이썬 소켓 시간제한 설정과 관계없이 자체
의 연결 시간제한 에러를 반환할 수 있습니다.


시간제한과 "accept" 메서드
--------------------------

"getdefaulttimeout()"가 "None"이 아니면, "accept()" 메서드에서 반환된
소켓은 그 시간제한을 상속합니다. 그렇지 않으면, 동작은 리스닝 소켓의
설정에 따라 다릅니다:

* 리스닝 소켓이 *블로킹 모드* 나 *시간제한 모드*에 있으면, "accept()"
  에 의해 반환된 소켓은 *블로킹 모드*에 있습니다.

* 리스닝 소켓이 *비 블로킹 모드*에 있으면, "accept()"에 의해 반환된 소
  켓이 블로킹 모드인지 비 블로킹 모드인지는 운영 체제에 따라 다릅니다.
  플랫폼 간 동작을 보장하려면, 이 설정을 직접 재정의하는 것이 좋습니다
  .


예제
====

Here are four minimal example programs using the TCP/IP protocol: a
server that echoes all data that it receives back (servicing only one
client), and a client using it.  Note that a server must perform the
sequence "socket()", "bind()", "listen()", "accept()" (possibly
repeating the "accept()" to service more than one client), while a
client only needs the sequence "socket()", "connect()".  Also note
that the server does not "sendall()"/"recv()" on the socket it is
listening on but on the new socket returned by "accept()".

처음 두 예제는 IPv4만 지원합니다.

   # Echo server program
   import socket

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

   # Echo client program
   import socket

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

The next two examples are identical to the above two, but support both
IPv4 and IPv6. The server side will listen to the first address family
available (it should listen to both instead). On most of IPv6-ready
systems, IPv6 will take precedence and the server may not accept IPv4
traffic. The client side will try to connect to all the addresses
returned as a result of the name resolution, and sends traffic to the
first one connected successfully.

   # 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 OSError as msg:
           s = None
           continue
       try:
           s.bind(sa)
           s.listen(1)
       except OSError as msg:
           s.close()
           s = None
           continue
       break
   if s is None:
       print('could not open socket')
       sys.exit(1)
   conn, addr = s.accept()
   with conn:
       print('Connected by', addr)
       while True:
           data = conn.recv(1024)
           if not data: break
           conn.send(data)

   # 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 OSError as msg:
           s = None
           continue
       try:
           s.connect(sa)
       except OSError as msg:
           s.close()
           s = None
           continue
       break
   if s is None:
       print('could not open socket')
       sys.exit(1)
   with s:
       s.sendall(b'Hello, world')
       data = s.recv(1024)
   print('Received', repr(data))

다음 예제는 윈도우에서 원시(raw) 소켓으로 매우 간단한 네트워크 스니퍼
를 작성하는 방법을 보여줍니다. 이 예제는 인터페이스를 수정하기 위해 관
리자 권한이 필요합니다:

   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 packets
   s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

   # receive a packet
   print(s.recvfrom(65565))

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

다음 예제는 원시(raw) 소켓 프로토콜을 사용하여, 소켓 인터페이스를 사용
하여 CAN 네트워크와 통신하는 방법을 보여줍니다. 대신 브로드캐스트 관리
자 프로토콜로 CAN을 사용하려면, 소켓을 이렇게 여십시오:

   socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)

After binding ("CAN_RAW") or connecting ("CAN_BCM") the socket, you
can use the "socket.send()" and "socket.recv()" operations (and their
counterparts) on the socket object as usual.

이 마지막 예제는 특별한 권한이 필요할 수 있습니다:

   import socket
   import struct


   # CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)

   can_frame_fmt = "=IB3x8s"
   can_frame_size = struct.calcsize(can_frame_fmt)

   def build_can_frame(can_id, data):
       can_dlc = len(data)
       data = data.ljust(8, b'\x00')
       return struct.pack(can_frame_fmt, can_id, can_dlc, data)

   def dissect_can_frame(frame):
       can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
       return (can_id, can_dlc, data[:can_dlc])


   # create a raw socket and bind it to the 'vcan0' interface
   s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
   s.bind(('vcan0',))

   while True:
       cf, addr = s.recvfrom(can_frame_size)

       print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))

       try:
           s.send(cf)
       except OSError:
           print('Error sending CAN frame')

       try:
           s.send(build_can_frame(0x01, b'\x01\x02\x03'))
       except OSError:
           print('Error sending CAN frame')

실행 간격이 너무 짧게 여러 번 예제를 실행하면 이 에러가 발생할 수 있습
니다:

   OSError: [Errno 98] Address already in use

이것은 이전 실행이 소켓을 "TIME_WAIT" 상태로 남겨 두었고, 즉시 재사용
할 수 없기 때문입니다.

There is a "socket" flag to set, in order to prevent this,
"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" 상태의 지역 소켓을 재사용하도록 커널에 알립니다.

더 보기:

  (C로 하는) 소켓 프로그래밍에 대한 소개는 다음 논문을 참조하십시오:

  * *An Introductory 4.3BSD Interprocess Communication Tutorial*,
    Stuart Sechrest 저

  * *An Advanced 4.3BSD Interprocess Communication Tutorial*, Samuel
    J. Leffler 외 저,

  둘 다 유닉스 프로그래머 매뉴얼, 보충 문서 1 (섹션 PS1:7과 PS1:8)에
  있습니다. 다양한 소켓 관련 시스템 호출에 대한 플랫폼별 레퍼런스 자료
  는 소켓 의미의 세부 정보에 대한 중요한 소스입니다. 유닉스에서는 매뉴
  얼 페이지를 참조하십시오; 윈도우에서는, WinSock (또는 Winsock 2) 명
  세를 참조하십시오. IPv6 지원 API의 경우, 독자는 Basic Socket
  Interface Extensions for IPv6라는 제목의 **RFC 3493**를 참조하고 싶
  을 겁니다.
