Ngoại lệ hết thời gian chờ ổ cắm python

Ổ cắm Python mới theo mặc định không có thời gian chờ. Thời gian chờ của nó mặc định là Không có. Không đặt tham số thời gian chờ kết nối có thể dẫn đến chế độ ổ cắm bị chặn. Ở chế độ chặn, các thao tác sẽ chặn cho đến khi hoàn thành hoặc hệ thống trả về lỗi

ID máy dò

python/socket-connection-timeout@v1. 0

Bảng liệt kê điểm yếu chung (CWE)


PyErr_SetString(PyErr_TimeoutError, "msg") and raise TimeoutError("msg") do not set any additional exception attributes. errno, strerror, filename, and filename2 are None:

>>> try:
..     raise TimeoutError("msg")
.. except Exception as e:
..     err = e
.. 
>>> err
TimeoutError('msg')
>>> (err.errno, err.filename, err.filename2, err.strerror)
(None, None, None, None)

Is that a problem?
> Isn't it a job of crossplatform programming language to abstract from
> low-level platform details?

It's certainly not Python's job. It's an explicit design goal, and a
long tradition, to expose system interfaces *as is*, with the very
same parameters, and the very same error codes. This is useful for
developers who need to understand what problem they encounter - they
can trust that Python doesn't second-guess the operating system.

It might be useful to put a layer on top of the system interfaces,
but such a layer needs to use different names.

> The scope of this bug is not about handling all possible Winsock errors.
> It is about proper handling the sole timeout error from the list
> http://www.winsock-error.com/ to make socket.connect() interface
> consistent for both windows and linux.

That's nearly impossible, with respect to specific error conditions.
The TCP stacks are too different.

You can easily define an common (but useless) error handling scheme
yourself: catch Exception, and interpret it as "it didn't work".

> BTW, I have tested the behaviour on linux - the system timeout on socket
> does occur, but with different error code.
> 
> socket.error: (110, 'Connection timed out')
> 
> Note that the error message is different too. That means that to
> properly wait for service to appear (or retry to reconnect later if
> server is not available) you need to handle three error cases.

That's correct. However, you shouldn't look at the error message when
handling the error on Linux. Instead, you should check whether the
error code is errno.ETIMEDOUT. The error message is only meant for
a human reader. Also notice that possible other errors returned from
connect are EACCES, EPERM, EADDRINUSE, EAFNOSUPPORT, EAGAIN,
EALREADY, EBADF, ECONNREFUSED, EFAULT, EINPROGRESS, EINTR, EISCONN,
ENETUNREACH, ENOTSOCK.
Thanks for the insight.

Well the most logical thing for me for the OS to do, would have been:
1. Send an ARP request
2. At the first poll call, report a timeout if no response was received 
3. Repeat to 2. until the destination is considered unreachable
4. At the next connect call, fire off another ARP request
5. At the next poll call, if the response to the ARP sent in 5 was not received, report "No route to host" immediately because it is the last cached result (from 3)
6. Always report "No route to host" for the following calls (even if new ARP requests are sent)

With "ip -4 neigh" I can see that the neighbor is in FAILED state when the OSError error is reported, but immediately goes to INCOMPLETE state at the next connect call (because another ARP request is sent).
The behavior is the same with an IPv6 socket. By re-reading the NDP RFC (https://tools.ietf.org/html/rfc4861) I can understand why implementations behave like that. The RFC does not define the "FAILED" neighbor cache state, so "resolution failed" means "neighbor is not in the cache".
Linux has a delayed garbage collection for the neighbor cache, which is why we can sometimes see entries in FAILED state, but when a new socket tries to connect to the peer, the resolution starts again like nothing happened before.

So it's weird, but it conforms to the standard :)

Mô-đun này cung cấp quyền truy cập vào giao diện ổ cắm BSD. Nó có sẵn trên tất cả các hệ thống Unix, Windows, MacOS hiện đại và có thể là các nền tảng bổ sung

Ghi chú

Một số hành vi có thể phụ thuộc vào nền tảng, vì các cuộc gọi được thực hiện tới các API socket của hệ điều hành

không phải Emscripten, không phải WASI

Mô-đun này không hoạt động hoặc không khả dụng trên nền tảng WebAssugging

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)
6 và
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)
7. Xem để biết thêm thông tin

Giao diện Python là sự chuyển ngữ đơn giản của lệnh gọi hệ thống Unix và giao diện thư viện cho các ổ cắm sang kiểu hướng đối tượng của Python. hàm

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)
8 trả về một đối tượng ổ cắm có các phương thức thực hiện các lệnh gọi hệ thống ổ cắm khác nhau. Các loại tham số ở cấp độ cao hơn một chút so với trong giao diện C. như với các thao tác
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)
9 và
>>> 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))]
0 trên các tệp Python, việc phân bổ bộ đệm cho các thao tác nhận là tự động và độ dài bộ đệm ẩn trong các thao tác gửi

Xem thêm

mô-đun

Các lớp đơn giản hóa việc viết máy chủ mạng

mô-đun

Trình bao bọc TLS/SSL cho các đối tượng ổ cắm

Họ ổ cắm

Tùy thuộc vào hệ thống và các tùy chọn xây dựng, các họ ổ cắm khác nhau được mô-đun này hỗ trợ

Định dạng địa chỉ được yêu cầu bởi một đối tượng ổ cắm cụ thể được chọn tự động dựa trên họ địa chỉ được chỉ định khi đối tượng ổ cắm được tạo. Địa chỉ ổ cắm được biểu diễn như sau

  • Địa chỉ của ổ cắm được liên kết với nút hệ thống tệp được biểu diễn dưới dạng chuỗi, sử dụng mã hóa hệ thống tệp và trình xử lý lỗi

    >>> 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))]
    
    4 (xem PEP 383). Một địa chỉ trong không gian tên trừu tượng của Linux được trả về dưới dạng a với byte null ban đầu; . Một đối tượng giống như chuỗi hoặc byte có thể được sử dụng cho một trong hai loại địa chỉ khi chuyển nó làm đối số

    Đã thay đổi trong phiên bản 3. 3. Trước đây, đường dẫn ổ cắm được cho là sử dụng mã hóa UTF-8.

    Đã thay đổi trong phiên bản 3. 5. Có thể ghi hiện được chấp nhận.

  • Một cặp

    >>> 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))]
    
    6 được sử dụng cho họ địa chỉ, trong đó máy chủ lưu trữ là một chuỗi đại diện cho tên máy chủ trong ký hiệu miền internet như
    >>> 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))]
    
    8 hoặc địa chỉ IPv4 như
    >>> 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))]
    
    9 và cổng là một số nguyên

    • Đối với địa chỉ IPv4, hai hình thức đặc biệt được chấp nhận thay vì địa chỉ máy chủ lưu trữ.

      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)
      
      0 đại diện cho
      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)
      
      1, được sử dụng để liên kết với tất cả các giao diện và chuỗi
      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)
      
      2 đại diện cho
      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)
      
      3. Hành vi này không tương thích với IPv6, do đó, bạn có thể muốn tránh những điều này nếu bạn có ý định hỗ trợ IPv6 với các chương trình Python của mình

  • Đối với họ địa chỉ, một bộ bốn bộ

    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)
    
    5 được sử dụng, trong đó flowinfo và scope_id đại diện cho các thành viên
    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)
    
    6 và
    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)
    
    7 trong
    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)
    
    8 trong C. Đối với các phương thức mô-đun, có thể bỏ qua flowinfo và scope_id để tương thích ngược. Tuy nhiên, xin lưu ý rằng việc bỏ qua scope_id có thể gây ra sự cố khi thao tác với các địa chỉ IPv6 có phạm vi

    Đã thay đổi trong phiên bản 3. 7. Đối với địa chỉ multicast (với scope_id có ý nghĩa), địa chỉ không được chứa phần

    >>> 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---')]
    
    0 (hoặc
    >>> 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---')]
    
    1). Thông tin này là không cần thiết và có thể được bỏ qua một cách an toàn (được khuyến nghị).

  • >>> 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---')]
    
    2 ổ cắm được biểu diễn dưới dạng cặp
    >>> 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---')]
    
    3

  • Hỗ trợ TIPC chỉ dành cho Linux có sẵn bằng cách sử dụng họ địa chỉ

    >>> 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---')]
    
    4. TIPC là một giao thức nối mạng mở, không dựa trên IP được thiết kế để sử dụng trong môi trường máy tính nhóm. Địa chỉ được đại diện bởi một bộ và các trường phụ thuộc vào loại địa chỉ. Dạng bộ dữ liệu chung là
    >>> 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---')]
    
    5, trong đó

    • addr_type là một trong số

      >>> 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---')]
      
      6,
      >>> 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---')]
      
      7 hoặc
      >>> 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---')]
      
      8

    • phạm vi là một trong số

      >>> 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---')]
      
      9,
      import socket, array
      
      def send_fds(sock, msg, fds):
          return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
      
      0 và
      import socket, array
      
      def send_fds(sock, msg, fds):
          return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
      
      1

    • Nếu addr_type là

      >>> 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---')]
      
      7, thì v1 là loại máy chủ, v2 là mã định danh cổng và v3 phải là 0

      Nếu addr_type là

      >>> 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---')]
      
      6, thì v1 là loại máy chủ, v2 là số cổng dưới và v3 là số cổng trên

      Nếu addr_type là

      >>> 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---')]
      
      8, thì v1 là nút, v2 là tham chiếu và v3 phải được đặt thành 0

  • Một tuple

    import socket, array
    
    def send_fds(sock, msg, fds):
        return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
    
    5 được sử dụng cho họ địa chỉ, trong đó giao diện là một chuỗi đại diện cho tên giao diện mạng như
    import socket, array
    
    def send_fds(sock, msg, fds):
        return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
    
    7. Tên giao diện mạng
    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)
    
    0 có thể được sử dụng để nhận các gói từ tất cả các giao diện mạng của họ này

    • giao thức yêu cầu một tuple

      # 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)
      
      0 trong đó cả hai tham số bổ sung đều là số nguyên dài không dấu đại diện cho mã định danh CAN (tiêu chuẩn hoặc mở rộng)

    • giao thức yêu cầu bộ dữ liệu

      # 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)
      
      2 trong đó các tham số bổ sung là số nguyên không dấu 64 bit biểu thị tên ECU, số nguyên không dấu 32 bit biểu thị Số nhóm tham số (PGN) và số nguyên 8 bit biểu thị địa chỉ

  • Một chuỗi hoặc một bộ

    # 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)
    
    3 được sử dụng cho giao thức
    # 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)
    
    4 của họ
    # 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)
    
    5. Chuỗi là tên của điều khiển hạt nhân sử dụng ID được gán động. Bộ dữ liệu có thể được sử dụng nếu biết ID và số đơn vị của điều khiển hạt nhân hoặc nếu ID đã đăng ký được sử dụng

    Mới trong phiên bản 3. 3

  • # 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)
    
    6 hỗ trợ các giao thức và định dạng địa chỉ sau

    • # 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)
      
      7 chấp nhận
      # 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)
      
      8 trong đó
      # 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)
      
      9 là địa chỉ Bluetooth dưới dạng chuỗi và
      # 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))
      
      0 là số nguyên

    • # 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))
      
      1 chấp nhận
      # 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))
      
      2 trong đó
      # 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)
      
      9 là địa chỉ Bluetooth dưới dạng chuỗi và
      # 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))
      
      4 là số nguyên

    • # 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))
      
      5 chấp nhận
      # 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))
      
      6 trong đó
      # 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))
      
      7 là số nguyên hoặc chuỗi có địa chỉ Bluetooth của giao diện. (Điều này phụ thuộc vào hệ điều hành của bạn; NetBSD và DragonFlyBSD mong đợi một địa chỉ Bluetooth trong khi mọi thứ khác mong đợi một số nguyên. )

      Đã thay đổi trong phiên bản 3. 2. Đã thêm hỗ trợ NetBSD và DragonFlyBSD.

    • # 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))
      
      8 chấp nhận
      # 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)
      
      9 trong đó
      # 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)
      
      9 là một đối tượng chứa địa chỉ Bluetooth ở định dạng chuỗi. (bán tại.
      # 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)
      
      2) Giao thức này không được hỗ trợ trong FreeBSD

  • là giao diện dựa trên ổ cắm chỉ dành cho Linux đối với mật mã Kernel. Một ổ cắm thuật toán được cấu hình với một bộ gồm hai đến bốn phần tử

    # 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)
    
    4, trong đó

    • type là kiểu thuật toán dưới dạng string, e. g.

      # 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)
      
      5,
      # 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)
      
      6,
      # 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)
      
      7 hoặc
      # 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)
      
      8

    • name là tên thuật toán và chế độ hoạt động dưới dạng chuỗi, e. g.

      # 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)
      
      9,
      # 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))
      
      0,
      # 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))
      
      1 hoặc
      # 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))
      
      2

    • sợ hãi và mặt nạ là số nguyên 32 bit không dấu

    Linux >= 2. 6. 38

    Một số loại thuật toán yêu cầu Kernel gần đây hơn

    Mới trong phiên bản 3. 6

  • cho phép giao tiếp giữa các máy ảo và máy chủ của chúng. Ổ cắm được biểu diễn dưới dạng bộ dữ liệu

    # 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))
    
    4 trong đó ID ngữ cảnh hoặc CID và cổng là số nguyên

    Linux >= 3. 9

    Xem sock(7)

    Mới trong phiên bản 3. 7

  • là giao diện cấp thấp trực tiếp với các thiết bị mạng. Các gói được đại diện bởi tuple

    # 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))
    
    6 trong đó

    • ifname - Chuỗi chỉ định tên thiết bị

    • proto - Một số nguyên theo thứ tự byte mạng chỉ định số giao thức Ethernet

    • pkttype - Số nguyên tùy chọn chỉ định loại gói

      • # 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))
        
        7 (mặc định) - Gói được gửi đến máy chủ lưu trữ cục bộ

      • # 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))
        
        8 - Gói quảng bá lớp vật lý

      • # 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))
        
        9 - Gói được gửi đến địa chỉ multicast lớp vật lý

      • 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)
        
        00 - Gói đến một số máy chủ khác đã bị trình điều khiển thiết bị bắt ở chế độ hỗn tạp

      • 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)
        
        01 - Gói có nguồn gốc từ máy chủ lưu trữ cục bộ được lặp lại vào ổ cắm gói

    • hatype - Số nguyên tùy chọn chỉ định loại địa chỉ phần cứng ARP

    • addr - Đối tượng giống như byte tùy chọn chỉ định địa chỉ vật lý của phần cứng, việc diễn giải tùy thuộc vào thiết bị

    Linux >= 2. 2

  • là giao diện dựa trên ổ cắm chỉ dành cho Linux để giao tiếp với các dịch vụ chạy trên bộ đồng xử lý trong nền tảng Qualcomm. Họ địa chỉ được biểu diễn dưới dạng bộ dữ liệu

    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)
    
    03 trong đó nút và cổng là các số nguyên không âm

    Linux >= 4. 7

    Mới trong phiên bản 3. 8

  • 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)
    
    04 là một biến thể của UDP cho phép bạn chỉ định phần nào của gói được bao phủ bởi tổng kiểm tra. Nó thêm hai tùy chọn ổ cắm mà bạn có thể thay đổi.
    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)
    
    05 sẽ thay đổi phần nào của các gói gửi đi được bao phủ bởi tổng kiểm tra và
    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)
    
    06 sẽ lọc ra các gói bao gồm quá ít dữ liệu của chúng. Trong cả hai trường hợp,
    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)
    
    07 nên ở trong
    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)
    
    08

    Một ổ cắm như vậy phải được xây dựng với

    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)
    
    09 cho IPv4 hoặc
    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)
    
    10 cho IPv6

    Linux >= 2. 6. 20, FreeBSD >= 10. 1

    Mới trong phiên bản 3. 9

Nếu bạn sử dụng tên máy chủ trong phần máy chủ của địa chỉ ổ cắm IPv4/v6, thì chương trình có thể hiển thị hành vi không xác định, vì Python sử dụng địa chỉ đầu tiên được trả về từ độ phân giải DNS. Địa chỉ ổ cắm sẽ được phân giải khác thành địa chỉ IPv4/v6 thực tế, tùy thuộc vào kết quả từ độ phân giải DNS và/hoặc cấu hình máy chủ. Đối với hành vi xác định, hãy sử dụng địa chỉ số trong phần máy chủ

Tất cả các lỗi tăng ngoại lệ. Các ngoại lệ thông thường đối với các loại đối số không hợp lệ và điều kiện hết bộ nhớ có thể được nêu ra. Các lỗi liên quan đến ngữ nghĩa của ổ cắm hoặc địa chỉ hoặc một trong các lớp con của nó

Chế độ không chặn được hỗ trợ thông qua. Việc tổng quát hóa điều này dựa trên thời gian chờ được hỗ trợ thông qua

nội dung mô-đun

Mô-đun xuất các phần tử sau

ngoại lệ

ngoại lệ ổ cắm. lỗi

Một bí danh không dùng nữa của

Đã thay đổi trong phiên bản 3. 3. Sau PEP 3151, lớp này được đặt bí danh là.

ngoại lệ ổ cắm. lỗi

Một lớp con của , ngoại lệ này được đưa ra đối với các lỗi liên quan đến địa chỉ, tôi. e. đối với các chức năng sử dụng h_errno trong API POSIX C, bao gồm và. Giá trị đi kèm là một cặp

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)
20 đại diện cho một lỗi được trả về bởi lệnh gọi thư viện. h_errno là một giá trị số, trong khi chuỗi đại diện cho mô tả của h_errno, được trả về bởi hàm
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)
21 C

Đã thay đổi trong phiên bản 3. 3. Lớp này được tạo thành lớp con của.

ngoại lệ ổ cắm. gaierror

Một lớp con của , ngoại lệ này được đưa ra đối với các lỗi liên quan đến địa chỉ bởi và. Giá trị đi kèm là một cặp

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)
26 đại diện cho một lỗi được trả về bởi lệnh gọi thư viện. chuỗi đại diện cho mô tả lỗi, như được trả về bởi hàm
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)
27 C. Giá trị lỗi số sẽ khớp với một trong các hằng số
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)
28 được xác định trong mô-đun này

Đã thay đổi trong phiên bản 3. 3. Lớp này được tạo thành lớp con của.

ngoại lệ ổ cắm. hết giờ

Một bí danh không dùng nữa của

Một lớp con của , ngoại lệ này được đưa ra khi thời gian chờ xảy ra trên ổ cắm đã hết thời gian chờ được bật thông qua lệnh gọi trước tới (hoặc ngầm định thông qua ). Giá trị đi kèm là một chuỗi có giá trị hiện tại luôn ở trạng thái “timed out”

Đã thay đổi trong phiên bản 3. 3. Lớp này được tạo thành lớp con của.

Đã thay đổi trong phiên bản 3. 10. Lớp này được đặt bí danh là.

hằng số

Các hằng số AF_* và SOCK__* hiện là các tập hợp

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)
36 và
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)
37

Mới trong phiên bản 3. 4

ổ cắm. AF_UNIXổ cắm. AF_INETổ cắm. AF_INET6

Các hằng số này đại diện cho các họ địa chỉ (và giao thức), được sử dụng cho đối số đầu tiên của

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)
8. Nếu hằng số không được xác định thì giao thức này không được hỗ trợ. Có thể có nhiều hằng số hơn tùy thuộc vào hệ thống

ổ cắm. SOCK_STREAMổ cắm. SOCK_DGRAMổ cắm. SOCK_RAWổ cắm. SOCK_RDMổ cắm. SOCK_SEQPACKET

Các hằng số này đại diện cho các loại ổ cắm, được sử dụng cho đối số thứ hai của

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)
8. Có thể có nhiều hằng số hơn tùy thuộc vào hệ thống. (Chỉ và dường như là hữu ích nói chung. )

ổ cắm. SOCK_CLOEXECổ cắm. SOCK_NONBLOCK

Hai hằng số này, nếu được xác định, có thể được kết hợp với các loại ổ cắm và cho phép bạn đặt một số cờ một cách nguyên tử (do đó tránh được các điều kiện chạy đua có thể xảy ra và nhu cầu gọi riêng)

Xem thêm

Xử lý mô tả tệp an toàn để được giải thích kỹ lưỡng hơn

Linux >= 2. 6. 27

Mới trong phiên bản 3. 2

SO_*ổ cắm. SOMAXCONNMSG_*SOL_*SCM_*IPPROTO_*IPPORT_*INADDR_*IP_*IPV6_*EAI_*AI_*NI_*TCP_*

Nhiều hằng số của các dạng này, được ghi lại trong tài liệu Unix về ổ cắm và/hoặc giao thức IP, cũng được xác định trong mô-đun ổ cắm. Chúng thường được sử dụng trong các đối số cho các phương thức

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)
44 và
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)
45 của các đối tượng ổ cắm. Trong hầu hết các trường hợp, chỉ những ký hiệu được xác định trong tệp tiêu đề Unix mới được xác định;

Đã thay đổi trong phiên bản 3. 6. _______3_______46,

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)
47,
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)
48,
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)
49,
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)
50,
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)
51 đã được thêm vào.

Đã thay đổi trong phiên bản 3. 6. 5. Trên Windows,

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)
52,
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)
53 xuất hiện nếu Windows hỗ trợ thời gian chạy.

Đã thay đổi trong phiên bản 3. 7. ______3_______54 đã được thêm vào.

Trên Windows,

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)
55,
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)
56 xuất hiện nếu thời gian chạy Windows hỗ trợ

Đã thay đổi trong phiên bản 3. 10. ______3_______57 đã được thêm vào. Đã thêm

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)
58. Trên MacOS, hằng số này có thể được sử dụng giống như cách mà
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)
55 được sử dụng trên Linux.

Đã thay đổi trong phiên bản 3. 11. Đã thêm

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)
60. Trên MacOS, hằng số này có thể được sử dụng giống như cách mà
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)
61 được sử dụng trên Linux và BSD.

ổ cắm. AF_CANổ cắm. PF_CANSOL_CAN_*CAN_*

Nhiều hằng số của các dạng này, được ghi lại trong tài liệu Linux, cũng được định nghĩa trong mô-đun ổ cắm

Linux >= 2. 6. 25, NetBSD >= 8

Mới trong phiên bản 3. 3

Đã thay đổi trong phiên bản 3. 11. Đã thêm hỗ trợ NetBSD.

ổ cắm. CAN_BCMCAN_BCM_*

CAN_BCM, trong họ giao thức CAN, là giao thức quản lý quảng bá (BCM). Các hằng số của trình quản lý phát sóng, được ghi lại trong tài liệu Linux, cũng được xác định trong mô-đun ổ cắm

Linux >= 2. 6. 25

Ghi chú

Cờ

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)
62 chỉ khả dụng trên Linux >= 4. 8

Mới trong phiên bản 3. 4

ổ cắm. CAN_RAW_FD_FRAMES

Cho phép hỗ trợ CAN FD trong ổ cắm CAN_RAW. Điều này bị tắt theo mặc định. Điều này cho phép ứng dụng của bạn gửi cả khung CAN và CAN FD;

Hằng số này được ghi lại trong tài liệu Linux

Linux >= 3. 6

Mới trong phiên bản 3. 5

ổ cắm. CAN_RAW_JOIN_FILTERS

Tham gia các bộ lọc CAN được áp dụng sao cho chỉ các khung CAN khớp với tất cả các bộ lọc CAN đã cho mới được chuyển đến không gian người dùng

Hằng số này được ghi lại trong tài liệu Linux

Linux >= 4. 1

Mới trong phiên bản 3. 9

ổ cắm. CAN_ISOTP

CAN_ISOTP, trong họ giao thức CAN, là giao thức ISO-TP (ISO 15765-2). Các hằng số ISO-TP, được ghi lại trong tài liệu Linux

Linux >= 2. 6. 25

Mới trong phiên bản 3. 7

ổ cắm. CAN_J1939

CAN_J1939, trong họ giao thức CAN, là giao thức SAE J1939. Các hằng số J1939, được ghi lại trong tài liệu Linux

Linux >= 5. 4

Mới trong phiên bản 3. 9

ổ cắm. AF_PACKETổ cắm. PF_PACKETPACKET_*

Nhiều hằng số của các dạng này, được ghi lại trong tài liệu Linux, cũng được định nghĩa trong mô-đun ổ cắm

Linux >= 2. 2

ổ cắm. AF_RDSổ cắm. ổ cắm PF_RDS. SOL_RDSRDS_*

Nhiều hằng số của các dạng này, được ghi lại trong tài liệu Linux, cũng được định nghĩa trong mô-đun ổ cắm

Linux >= 2. 6. 30

Mới trong phiên bản 3. 3

ổ cắm. SIO_RCVALLổ cắm. SIO_KEEPALIVE_VALSổ cắm. SIO_LOOPBACK_FAST_PATHRCVALL_*

Các hằng số cho WSAIoctl() của Windows. Các hằng số được sử dụng làm đối số cho phương thức của các đối tượng socket

Đã thay đổi trong phiên bản 3. 6. ______3_______64 đã được thêm vào.

MẸO_*

Các hằng số liên quan đến TIPC, khớp với các hằng số được xuất bởi API ổ cắm C. Xem tài liệu TIPC để biết thêm thông tin

ổ cắm. AF_ALGổ cắm. SOL_ALGALG_*

Các hằng số cho mã hóa hạt nhân Linux

Linux >= 2. 6. 38

Mới trong phiên bản 3. 6

ổ cắm. AF_VSOCKổ cắm. IOCTL_VM_SOCKETS_GET_LOCAL_CIDVMADDR*SO_VM*

Các hằng số cho giao tiếp máy chủ/khách Linux

Linux >= 4. 8

Mới trong phiên bản 3. 7

ổ cắm. AF_LINK

BSD, macOS

Mới trong phiên bản 3. 4

ổ cắm. has_ipv6

Hằng số này chứa một giá trị boolean cho biết liệu IPv6 có được hỗ trợ trên nền tảng này hay không

ổ cắm. BDADDR_ANYổ cắm. BDADDR_LOCAL

Đây là các hằng chuỗi chứa địa chỉ Bluetooth có ý nghĩa đặc biệt. Ví dụ: có thể được sử dụng để chỉ ra bất kỳ địa chỉ nào khi chỉ định ổ cắm liên kết với

# 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))
1

ổ cắm. HCI_FILTERổ cắm. ổ cắm HCI_TIME_STAMP. HCI_DATA_DIR

Để sử dụng với

# 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))
5. không có sẵn cho NetBSD hoặc DragonFlyBSD. và không khả dụng cho FreeBSD, NetBSD hoặc DragonFlyBSD

ổ cắm. AF_QIPCRTR

Hằng số cho giao thức bộ định tuyến IPC của Qualcomm, được sử dụng để giao tiếp với dịch vụ cung cấp bộ xử lý từ xa

Linux >= 4. 7

ổ cắm. SCM_CREDS2ổ cắm. LOCAL_CREDSổ cắm. LOCAL_CREDS_PERSISTENT

LOCAL_CREDS và LOCAL_CREDS_PERSISTENT có thể được sử dụng với ổ cắm SOCK_DGRAM, SOCK_STREAM, tương đương với Linux/DragonFlyBSD SO_PASSCRED, trong khi LOCAL_CREDS gửi thông tin đăng nhập ở lần đọc đầu tiên, LOCAL_CREDS_PERSISTENT gửi cho mỗi lần đọc, SCM_CREDS2 sau đó phải được sử dụng cho lần đọc sau đối với loại thông báo

Mới trong phiên bản 3. 11

BSD miễn phí

ổ cắm. SO_INCOMING_CPU

Hằng số để tối ưu hóa vị trí CPU, được sử dụng cùng với

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)
71

Mới trong phiên bản 3. 11

Linux >= 3. 9

Chức năng

Tạo ổ cắm

Tất cả các chức năng sau đây tạo ra

lớp . ổ cắm(gia đình=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)

Tạo một ổ cắm mới bằng cách sử dụng họ địa chỉ, loại ổ cắm và số giao thức đã cho. Họ địa chỉ phải là (mặc định), , , , hoặc. Loại ổ cắm phải là (mặc định), hoặc có lẽ là một trong các hằng số

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)
81 khác. Số giao thức thường bằng 0 và có thể bị bỏ qua hoặc trong trường hợp họ địa chỉ là giao thức thì giao thức phải là một trong số
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)
83, , hoặc

Nếu fileno được chỉ định, các giá trị cho họ, loại và nguyên mẫu được tự động phát hiện từ bộ mô tả tệp đã chỉ định. Tự động phát hiện có thể bị ghi đè bằng cách gọi hàm với các đối số họ, loại hoặc proto rõ ràng. Điều này chỉ ảnh hưởng đến cách Python đại diện cho e. g. giá trị trả về nhưng không phải là tài nguyên hệ điều hành thực tế. Không giống như, fileno sẽ trả về cùng một ổ cắm và không trùng lặp. Điều này có thể giúp đóng một ổ cắm tách rời bằng cách sử dụng

Ổ cắm mới được tạo là

Tăng một

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)
90 với các đối số
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)
91,
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)
92,
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)
93,
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)
94

Đã thay đổi trong phiên bản 3. 3. Dòng AF_CAN đã được thêm vào. Họ AF_RDS đã được thêm vào.

Đã thay đổi trong phiên bản 3. 4. Giao thức CAN_BCM đã được thêm vào.

Đã thay đổi trong phiên bản 3. 4. Ổ cắm được trả về hiện không thể kế thừa.

Đã thay đổi trong phiên bản 3. 7. Giao thức CAN_ISOTP đã được thêm vào.

Đã thay đổi trong phiên bản 3. 7. Khi hoặc cờ bit được áp dụng cho loại, chúng sẽ bị xóa và sẽ không phản ánh chúng. Chúng vẫn được chuyển đến cuộc gọi

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)
8 của hệ thống cơ bản. Vì vậy,

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

vẫn sẽ tạo non-blocking socket trên các hệ điều hành hỗ trợ

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)
95, nhưng
>>> 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))]
00 sẽ được đặt thành
>>> 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))]
01

Đã thay đổi trong phiên bản 3. 9. Giao thức CAN_J1939 đã được thêm vào.

Đã thay đổi trong phiên bản 3. 10. Giao thức IPPROTO_MPTCP đã được thêm vào.

ổ cắm. cặp ổ cắm([gia đình[, type[, proto]]])

Xây dựng một cặp đối tượng ổ cắm được kết nối bằng cách sử dụng họ địa chỉ, loại ổ cắm và số giao thức đã cho. Họ địa chỉ, loại ổ cắm và số giao thức giống như hàm

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)
8 ở trên. Họ mặc định là nếu được xác định trên nền tảng;

Các ổ cắm mới được tạo là

Đã thay đổi trong phiên bản 3. 2. Các đối tượng ổ cắm được trả về hiện hỗ trợ toàn bộ API ổ cắm, thay vì một tập hợp con.

Đã thay đổi trong phiên bản 3. 4. Các ổ cắm được trả lại hiện không thể kế thừa.

Đã thay đổi trong phiên bản 3. 5. Đã thêm hỗ trợ Windows.

ổ cắm. create_connection(địa chỉ , thời gian chờ=GLOBAL_DEFAULT, source_address=None, *, all_errors=False)

Kết nối với dịch vụ TCP đang nghe trên địa chỉ internet (2-tuple

>>> 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))]
6) và trả về đối tượng ổ cắm. Đây là một chức năng cấp cao hơn so với. nếu máy chủ lưu trữ là một tên máy chủ không phải dạng số, nó sẽ cố gắng phân giải nó cho cả và , sau đó lần lượt cố gắng kết nối với tất cả các địa chỉ có thể cho đến khi kết nối thành công. Điều này giúp dễ dàng viết các ứng dụng khách tương thích với cả IPv4 và IPv6

Truyền tham số thời gian chờ tùy chọn sẽ đặt thời gian chờ trên phiên bản ổ cắm trước khi thử kết nối. Nếu không có thời gian chờ nào được cung cấp, cài đặt thời gian chờ mặc định chung được trả về sẽ được sử dụng

Nếu được cung cấp, source_address phải là 2-tuple

>>> 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))]
6 để ổ cắm liên kết thành địa chỉ nguồn của nó trước khi kết nối. Nếu máy chủ hoặc cổng tương ứng là ‘’ hoặc 0 thì hành vi mặc định của hệ điều hành sẽ được sử dụng

Khi không thể tạo kết nối, một ngoại lệ được đưa ra. Theo mặc định, nó là ngoại lệ từ địa chỉ cuối cùng trong danh sách. Nếu all_errors là

>>> 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))]
11, thì nó chứa lỗi của tất cả các lần thử

Đã thay đổi trong phiên bản 3. 2. source_address đã được thêm.

Đã thay đổi trong phiên bản 3. 11. all_errors đã được thêm vào.

ổ cắm. create_server(địa chỉ , *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False)

Hàm tiện lợi tạo ổ cắm TCP được liên kết với địa chỉ (2-tuple

>>> 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))]
6) và trả về đối tượng ổ cắm

gia đình nên là một trong hai hoặc. tồn đọng là kích thước hàng đợi được chuyển đến; . tái sử dụng_port cho biết có nên đặt tùy chọn ổ cắm

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)
71 hay không

Nếu dualstack_ipv6 là đúng và nền tảng hỗ trợ thì ổ cắm sẽ có thể chấp nhận cả kết nối IPv4 và IPv6, nếu không thì nó sẽ tăng. Hầu hết các nền tảng POSIX và Windows được cho là hỗ trợ chức năng này. Khi chức năng này được bật, địa chỉ được trả về khi xảy ra kết nối IPv4 sẽ là địa chỉ IPv6 được biểu thị dưới dạng địa chỉ IPv6 được ánh xạ IPv4. Nếu dualstack_ipv6 là false, nó sẽ vô hiệu hóa chức năng này một cách rõ ràng trên các nền tảng kích hoạt nó theo mặc định (e. g. Linux). Tham số này có thể được sử dụng kết hợp với

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)

Ghi chú

Trên nền tảng POSIX, tùy chọn ổ cắm

>>> 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))]
21 được đặt để sử dụng lại ngay các ổ cắm trước đó được liên kết trên cùng một địa chỉ và duy trì ở trạng thái TIME_WAIT

Mới trong phiên bản 3. 8

ổ cắm. has_dualstack_ipv6()

Trả lại

>>> 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))]
11 nếu nền tảng hỗ trợ tạo ổ cắm TCP có thể xử lý cả kết nối IPv4 và IPv6

Mới trong phiên bản 3. 8

ổ cắm. từfd(fd , gia đình, type, proto=0)

Sao chép bộ mô tả tệp fd (một số nguyên như được trả về bởi phương thức

>>> 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))]
23 của đối tượng tệp) và xây dựng một đối tượng ổ cắm từ kết quả. Họ địa chỉ, loại ổ cắm và số giao thức giống như chức năng
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)
8 ở trên. Bộ mô tả tệp phải tham chiếu đến một ổ cắm, nhưng điều này không được chọn — các thao tác tiếp theo trên đối tượng có thể thất bại nếu bộ mô tả tệp không hợp lệ. Chức năng này hiếm khi cần thiết, nhưng có thể được sử dụng để nhận hoặc đặt các tùy chọn ổ cắm trên một ổ cắm được chuyển đến chương trình dưới dạng đầu vào hoặc đầu ra tiêu chuẩn (chẳng hạn như máy chủ được khởi động bởi Unix inet daemon). Ổ cắm được coi là ở chế độ chặn

Ổ cắm mới được tạo là

Đã thay đổi trong phiên bản 3. 4. Ổ cắm được trả về hiện không thể kế thừa.

ổ cắm. từ chia sẻ(dữ liệu)

Khởi tạo một ổ cắm từ dữ liệu thu được từ phương thức. Ổ cắm được coi là ở chế độ chặn

các cửa sổ

Mới trong phiên bản 3. 3

ổ cắm. Loại ổ cắm

Đây là một đối tượng kiểu Python đại diện cho kiểu đối tượng ổ cắm. Nó giống như

>>> 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))]
26

Cac chưc năng khac

Mô-đun này cũng cung cấp các dịch vụ liên quan đến mạng khác nhau

ổ cắm. đóng(fd)

Đóng bộ mô tả tệp ổ cắm. Điều này giống như , nhưng đối với ổ cắm. Trên một số nền tảng (đáng chú ý nhất là Windows) không hoạt động đối với bộ mô tả tệp ổ cắm

Mới trong phiên bản 3. 7

ổ cắm. getaddrinfo(máy chủ , cổng, family=0, type=0, proto=0, flags=0)

Dịch đối số máy chủ/cổng thành một chuỗi gồm 5 bộ chứa tất cả các đối số cần thiết để tạo ổ cắm được kết nối với dịch vụ đó. máy chủ lưu trữ là một tên miền, một đại diện chuỗi của địa chỉ IPv4/v6 hoặc

>>> 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))]
30. cổng là một tên dịch vụ chuỗi, chẳng hạn như
>>> 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))]
31, số cổng dạng số hoặc
>>> 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))]
30. Bằng cách chuyển
>>> 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))]
30 làm giá trị của máy chủ và cổng, bạn có thể chuyển
>>> 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))]
34 cho API C bên dưới

Các đối số họ, loại và nguyên mẫu có thể được chỉ định tùy chọn để thu hẹp danh sách địa chỉ được trả về. Việc chuyển số 0 làm giá trị cho từng đối số này sẽ chọn toàn bộ phạm vi kết quả. Đối số flags có thể là một hoặc một vài trong số các hằng số

>>> 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))]
35 và sẽ ảnh hưởng đến cách tính toán và trả về kết quả. Ví dụ:
>>> 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))]
36 sẽ vô hiệu hóa độ phân giải tên miền và sẽ gây ra lỗi nếu máy chủ lưu trữ là một tên miền

Hàm trả về danh sách 5 bộ có cấu trúc sau

>>> 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))]
37

Trong các bộ này, family, type, proto đều là số nguyên và được truyền cho hàm

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)
8. canonname sẽ là một chuỗi đại diện cho tên chuẩn của máy chủ lưu trữ nếu
>>> 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))]
39 là một phần của đối số flags; . sockaddr là một bộ mô tả một địa chỉ ổ cắm, có định dạng phụ thuộc vào họ được trả về (một bộ 2 ______________40 cho , một bộ 4 __________42 cho ) và có nghĩa là được truyền cho phương thức

Nâng cao một

>>> 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))]
45 với các đối số
>>> 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))]
46,
>>> 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))]
47,
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)
92,
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)
93,
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)
94

Ví dụ sau tìm nạp thông tin địa chỉ cho một kết nối TCP giả định tới

>>> 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))]
51 trên cổng 80 (kết quả có thể khác trên hệ thống của bạn nếu IPv6 không được bật)

>>> 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))]

Đã thay đổi trong phiên bản 3. 2. các tham số hiện có thể được chuyển bằng các đối số từ khóa.

Đã thay đổi trong phiên bản 3. 7. đối với địa chỉ multicast IPv6, chuỗi biểu thị địa chỉ sẽ không chứa phần

>>> 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---')]
0.

ổ cắm. getfqdn([tên])

Trả lại một tên miền đủ điều kiện cho tên. Nếu tên bị bỏ qua hoặc trống, nó được hiểu là máy chủ lưu trữ cục bộ. Để tìm tên đủ điều kiện, tên máy chủ được trả về được chọn, theo sau là bí danh cho máy chủ, nếu có. Tên đầu tiên bao gồm một khoảng thời gian được chọn. Trong trường hợp không có tên miền đủ điều kiện và tên đã được cung cấp, nó sẽ được trả về không thay đổi. Nếu tên trống hoặc bằng

>>> 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))]
54, tên máy chủ từ được trả về

ổ cắm. gethostbyname(tên máy chủ)

Dịch tên máy chủ sang định dạng địa chỉ IPv4. Địa chỉ IPv4 được trả về dưới dạng một chuỗi, chẳng hạn như

>>> 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))]
9. Nếu tên máy chủ là một địa chỉ IPv4, nó được trả về không thay đổi. Xem để có giao diện đầy đủ hơn. không hỗ trợ độ phân giải tên IPv6 và nên được sử dụng thay thế cho hỗ trợ ngăn xếp kép IPv4/v6

Nâng cao một

>>> 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))]
60 với lập luận
>>> 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))]
61

không phải WASI

ổ cắm. gethostbyname_ex(tên máy chủ)

Dịch tên máy chủ sang định dạng địa chỉ IPv4, giao diện mở rộng. Trả về một bộ ba

>>> 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))]
62 trong đó tên máy chủ là tên máy chủ chính của máy chủ lưu trữ, danh sách bí danh là danh sách (có thể trống) các tên máy chủ thay thế cho cùng một địa chỉ và ipaddrlist là danh sách các địa chỉ IPv4 cho cùng một giao diện trên cùng một máy chủ (thường nhưng không . không hỗ trợ độ phân giải tên IPv6 và nên được sử dụng thay thế cho hỗ trợ ngăn xếp kép IPv4/v6

Nâng cao một

>>> 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))]
60 với lập luận
>>> 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))]
61

không phải WASI

ổ cắm. gethostname()

Trả về một chuỗi chứa tên máy chủ mà trình thông dịch Python hiện đang thực thi

Tăng một

>>> 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))]
67 mà không có đối số

Ghi chú. không phải lúc nào cũng trả lại tên miền đủ điều kiện;

không phải WASI

ổ cắm. gethostbyaddr(ip_address)

Trả về bộ ba

>>> 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))]
62 trong đó tên máy chủ là tên máy chủ chính phản hồi ip_address đã cho, aliaslist là danh sách (có thể trống) các tên máy chủ thay thế cho cùng một địa chỉ và ipaddrlist là danh sách các địa chỉ IPv4/v6 cho cùng một giao diện trên . Để tìm tên miền đủ điều kiện, hãy sử dụng chức năng. hỗ trợ cả IPv4 và IPv6

Đưa ra một

>>> 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))]
73 với lập luận
>>> 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))]
74

không phải WASI

ổ cắm. getnameinfo(sockaddr , cờ)

Dịch địa chỉ ổ cắm sockaddr thành 2-tuple

>>> 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))]
6. Tùy thuộc vào cài đặt của cờ, kết quả có thể chứa một tên miền đủ điều kiện hoặc đại diện địa chỉ số trong máy chủ. Tương tự, cổng có thể chứa tên cổng chuỗi hoặc số cổng dạng số

Đối với địa chỉ IPv6,

>>> 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---')]
0 được thêm vào phần máy chủ lưu trữ nếu sockaddr chứa scope_id có ý nghĩa. Thông thường điều này xảy ra đối với các địa chỉ multicast

Để biết thêm thông tin về cờ, bạn có thể tham khảo getnameinfo(3)

Đưa ra một

>>> 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))]
77 với lập luận
>>> 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))]
78

không phải WASI

ổ cắm. getprotobyname(tên giao thức)

Dịch tên giao thức internet (ví dụ:

>>> 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))]
79) thành một hằng số phù hợp để chuyển làm đối số thứ ba (tùy chọn) cho hàm
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)
8. Điều này thường chỉ cần thiết cho các ổ cắm được mở ở chế độ "thô" ();

không phải WASI

ổ cắm. getservbyname(tên dịch vụ[ , protocolname])

Dịch tên dịch vụ internet và tên giao thức thành số cổng cho dịch vụ đó. Tên giao thức tùy chọn, nếu được cung cấp, phải là

>>> 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))]
82 hoặc
>>> 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))]
83, nếu không thì bất kỳ giao thức nào cũng sẽ khớp

Tăng một

>>> 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))]
84 với các đối số
>>> 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))]
85,
>>> 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))]
86

không phải WASI

ổ cắm. getservbyport(cổng[ , protocolname])

Dịch số cổng internet và tên giao thức thành tên dịch vụ cho dịch vụ đó. Tên giao thức tùy chọn, nếu được cung cấp, phải là

>>> 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))]
82 hoặc
>>> 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))]
83, nếu không thì bất kỳ giao thức nào cũng sẽ khớp

Tăng một

>>> 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))]
89 với các đối số
>>> 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))]
47,
>>> 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))]
86

không phải WASI

ổ cắm. ntohl(x)

Chuyển đổi số nguyên dương 32 bit từ mạng sang thứ tự byte lưu trữ. Trên các máy có thứ tự byte máy chủ giống với thứ tự byte mạng, đây là lệnh cấm;

ổ cắm. ntohs(x)

Chuyển đổi số nguyên dương 16 bit từ mạng sang thứ tự byte lưu trữ. Trên các máy có thứ tự byte máy chủ giống với thứ tự byte mạng, đây là lệnh cấm;

Đã thay đổi trong phiên bản 3. 10. Tăng nếu x không vừa với số nguyên không dấu 16 bit.

ổ cắm. htonl(x)

Chuyển đổi số nguyên dương 32 bit từ máy chủ sang thứ tự byte mạng. Trên các máy có thứ tự byte máy chủ giống với thứ tự byte mạng, đây là lệnh cấm;

ổ cắm. htons(x)

Chuyển đổi số nguyên dương 16 bit từ máy chủ sang thứ tự byte mạng. Trên các máy có thứ tự byte máy chủ giống với thứ tự byte mạng, đây là lệnh cấm;

Đã thay đổi trong phiên bản 3. 10. Tăng nếu x không vừa với số nguyên không dấu 16 bit.

ổ cắm. inet_aton(ip_string)

Chuyển đổi địa chỉ IPv4 từ định dạng chuỗi tứ giác chấm (ví dụ: '123. 45. 67. 89') sang định dạng nhị phân được đóng gói 32 bit, dưới dạng đối tượng byte có độ dài bốn ký tự. Điều này hữu ích khi trò chuyện với một chương trình sử dụng thư viện C tiêu chuẩn và cần các đối tượng thuộc loại

>>> 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))]
94, là loại C cho nhị phân được đóng gói 32 bit mà hàm này trả về

cũng chấp nhận các chuỗi có ít hơn ba dấu chấm;

Nếu chuỗi địa chỉ IPv4 được chuyển đến chức năng này không hợp lệ, sẽ tăng. Lưu ý rằng chính xác những gì hợp lệ phụ thuộc vào việc triển khai C cơ bản của

>>> 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))]
95

không hỗ trợ IPv6 và nên được sử dụng thay thế cho hỗ trợ ngăn xếp kép IPv4/v6

ổ cắm. inet_ntoa(packed_ip)

Chuyển đổi địa chỉ IPv4 được đóng gói 32 bit (độ dài bốn byte) thành biểu diễn chuỗi bốn dấu chấm tiêu chuẩn của nó (ví dụ: '123. 45. 67. 89’). This is useful when conversing with a program that uses the standard C library and needs objects of type

>>> 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))]
94, which is the C type for the 32-bit packed binary data this function takes as an argument

If the byte sequence passed to this function is not exactly 4 bytes in length, will be raised. does not support IPv6, and should be used instead for IPv4/v6 dual stack support

Đã thay đổi trong phiên bản 3. 5. Có thể ghi hiện được chấp nhận.

socket. inet_pton(address_family , ip_string)

Convert an IP address from its family-specific string format to a packed, binary format. is useful when a library or network protocol calls for an object of type

>>> 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))]
94 (similar to ) or
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)
07

Supported values for address_family are currently and . If the IP address string ip_string is invalid, will be raised. Note that exactly what is valid depends on both the value of address_family and the underlying implementation of

>>> 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))]
99

Unix, Windows

Changed in version 3. 4. Windows support added

socket. inet_ntop(address_family , packed_ip)

Convert a packed IP address (a of some number of bytes) to its standard, family-specific string representation (for example,

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)
12 or
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)
13). is useful when a library or network protocol returns an object of type
>>> 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))]
94 (similar to ) or
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)
07

Supported values for address_family are currently and . If the bytes object packed_ip is not the correct length for the specified address family, will be raised. is raised for errors from the call to

Unix, Windows

Changed in version 3. 4. Windows support added

Đã thay đổi trong phiên bản 3. 5. Có thể ghi hiện được chấp nhận.

socket. CMSG_LEN(length)

Trả về tổng độ dài, không có phần đệm ở cuối, của một mục dữ liệu phụ trợ với dữ liệu được liên kết có độ dài nhất định. This value can often be used as the buffer size for to receive a single item of ancillary data, but RFC 3542 requires portable applications to use and thus include space for padding, even when the item will be the last in the buffer. Raises if length is outside the permissible range of values

Unix, not Emscripten, not WASI

Most Unix platforms

Mới trong phiên bản 3. 3

socket. CMSG_SPACE(length)

Return the buffer size needed for to receive an ancillary data item with associated data of the given length, along with any trailing padding. The buffer space needed to receive multiple items is the sum of the values for their associated data lengths. Raises if length is outside the permissible range of values

Note that some systems might support ancillary data without providing this function. Also note that setting the buffer size using the results of this function may not precisely limit the amount of ancillary data that can be received, since additional data may be able to fit into the padding area

Unix, not Emscripten, not WASI

most Unix platforms

Mới trong phiên bản 3. 3

socket. getdefaulttimeout()

Return the default timeout in seconds (float) for new socket objects. A value of

>>> 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))]
30 indicates that new socket objects have no timeout. When the socket module is first imported, the default is
>>> 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))]
30

socket. setdefaulttimeout(timeout)

Set the default timeout in seconds (float) for new socket objects. When the socket module is first imported, the default is

>>> 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))]
30. See for possible values and their respective meanings

socket. sethostname(name)

Set the machine’s hostname to name. This will raise an if you don’t have enough rights

Raises an

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)
34 with argument
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)
35

Unix

Mới trong phiên bản 3. 3

socket. if_nameindex()

Return a list of network interface information (index int, name string) tuples. if the system call fails

Unix, Windows, not Emscripten, not WASI

Mới trong phiên bản 3. 3

Changed in version 3. 8. Windows support was added.

Ghi chú

On Windows network interfaces have different names in different contexts (all names are examples)

  • UUID.

    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)
    
    37

  • name.

    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)
    
    38

  • friendly name.

    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)
    
    39

  • description.

    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)
    
    40

This function returns names of the second form from the list,

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)
38 in this example case

socket. if_nametoindex(if_name)

Return a network interface index number corresponding to an interface name. if no interface with the given name exists

Unix, Windows, not Emscripten, not WASI

Mới trong phiên bản 3. 3

Changed in version 3. 8. Windows support was added.

Xem thêm

“Interface name” is a name as documented in

socket. if_indextoname(if_index)

Return a network interface name corresponding to an interface index number. if no interface with the given index exists

Unix, Windows, not Emscripten, not WASI

Mới trong phiên bản 3. 3

Changed in version 3. 8. Windows support was added.

Xem thêm

“Interface name” is a name as documented in

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

Send the list of file descriptors fds over an socket sock. The fds parameter is a sequence of file descriptors. Consult

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)
47 for the documentation of these parameters

Unix, Windows, not Emscripten, not WASI

Nền tảng Unix hỗ trợ và cơ chế

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)
49

Mới trong phiên bản 3. 9

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

Receive up to maxfds file descriptors from an socket sock. Return

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)
51. Consult
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)
23 for the documentation of these parameters

Unix, Windows, not Emscripten, not WASI

Nền tảng Unix hỗ trợ và cơ chế

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)
49

Mới trong phiên bản 3. 9

Ghi chú

Any truncated integers at the end of the list of file descriptors

Socket Objects

Socket objects have the following methods. Except for , these correspond to Unix system calls applicable to sockets

Changed in version 3. 2. Support for the protocol was added. Exiting the context manager is equivalent to calling .

socket. accept()

Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair

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)
57 where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection

Ổ cắm mới được tạo là

Changed in version 3. 4. The socket is now non-inheritable.

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an exception (see PEP 475 for the rationale).

socket. bind(address)

Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — see above. )

Raises an

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)
59 with arguments
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)
91,
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)
61

không phải WASI

socket. close()

Mark the socket closed. The underlying system resource (e. g. a file descriptor) is also closed when all file objects from 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)

Sockets are automatically closed when they are garbage-collected, but it is recommended to them explicitly, or to use a statement around them

Changed in version 3. 6. is now raised if an error occurs when the underlying

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)
56 call is made.

Ghi chú

giải phóng tài nguyên được liên kết với kết nối nhưng không nhất thiết phải đóng kết nối ngay lập tức. Nếu bạn muốn đóng kết nối kịp thời, hãy gọi trước

ổ cắm. kết nối(địa chỉ)

Kết nối với ổ cắm từ xa tại địa chỉ. (Định dạng của địa chỉ phụ thuộc vào họ địa chỉ — xem ở trên. )

Nếu kết nối bị gián đoạn bởi tín hiệu, phương thức sẽ đợi cho đến khi kết nối hoàn tất hoặc tăng thời gian chờ, nếu trình xử lý tín hiệu không đưa ra ngoại lệ và ổ cắm đang chặn hoặc hết thời gian chờ. Đối với các ổ cắm không chặn, phương pháp này sẽ đưa ra một ngoại lệ nếu kết nối bị gián đoạn bởi một tín hiệu (hoặc ngoại lệ do bộ xử lý tín hiệu đưa ra)

Tăng một

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)
72 với các đối số
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)
91,
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)
61

Changed in version 3. 5. Phương thức hiện đợi cho đến khi kết nối hoàn tất thay vì đưa ra ngoại lệ nếu kết nối bị gián đoạn bởi tín hiệu, trình xử lý tín hiệu không đưa ra ngoại lệ và ổ cắm đang bị chặn hoặc hết thời gian chờ ( .

không phải WASI

socket. connect_ex(address)

Like

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)
76, but return an error indicator instead of raising an exception for errors returned by the C-level
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)
77 call (other problems, such as “host not found,” can still raise exceptions). The error indicator is
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)
78 if the operation succeeded, otherwise the value of the
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)
79 variable. This is useful to support, for example, asynchronous connects

Tăng một

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)
72 với các đối số
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)
91,
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)
61

không phải WASI

socket. detach()

Đặt đối tượng ổ cắm vào trạng thái đóng mà không thực sự đóng bộ mô tả tệp bên dưới. The file descriptor is returned, and can be reused for other purposes

Mới trong phiên bản 3. 2

socket. dup()

Duplicate the socket

Ổ cắm mới được tạo là

Changed in version 3. 4. The socket is now non-inheritable.

không phải WASI

socket. fileno()

Return the socket’s file descriptor (a small integer), or -1 on failure. This is useful with

Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as ). Unix does not have this limitation

socket. get_inheritable()

Get the of the socket’s file descriptor or socket’s handle.

>>> 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))]
11 if the socket can be inherited in child processes,
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)
86 if it cannot

Mới trong phiên bản 3. 4

socket. getpeername()

Return the remote address to which the socket is connected. This is useful to find out the port number of a remote IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above. ) On some systems this function is not supported

socket. getsockname()

Return the socket’s own address. This is useful to find out the port number of an IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above. )

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

Return the value of the given socket option (see the Unix man page getsockopt(2)). The needed symbolic constants (

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)
87 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 for a way to decode C structures encoded as byte strings)

không phải WASI

socket. getblocking()

Return

>>> 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))]
11 if socket is in blocking mode,
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)
86 if in non-blocking

This is equivalent to checking

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)
91

Mới trong phiên bản 3. 7

socket. gettimeout()

Return the timeout in seconds (float) associated with socket operations, or

>>> 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))]
30 if no timeout is set. This reflects the last call to or

socket. ioctl(control , option) Platform

Windows

The method is a limited interface to the WSAIoctl system interface. Please refer to the Win32 documentation for more information

On other platforms, the generic and functions may be used; they accept a socket object as their first argument

Currently only the following control codes are supported.

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)
98,
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)
99, and
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)
64

Đã thay đổi trong phiên bản 3. 6. ______3_______64 đã được thêm vào.

socket. listen([backlog])

Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen

không phải WASI

Changed in version 3. 5. The backlog parameter is now optional.

socket. makefile(chế độ=', buffering=None, *, encoding=None, errors=None, newline=None)

Return a associated with the socket. The exact returned type depends on the arguments given to . These arguments are interpreted the same way as by the built-in function, except the only supported mode values are

>>> 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---')]
04 (default),
>>> 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---')]
05 and
>>> 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---')]
06

The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer may end up in an inconsistent state if a timeout occurs

Closing the file object returned by won’t close the original socket unless all other file objects have been closed and has been called on the socket object

Ghi chú

On Windows, the file-like object created by cannot be used where a file object with a file descriptor is expected, such as the stream arguments of

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. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero

Ghi chú

For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an exception (see PEP 475 for the rationale).

socket. recvfrom(bufsize[ , flags])

Receive data from the socket. The return value is a pair

>>> 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---')]
12 where bytes is a bytes object 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. )

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an exception (see PEP 475 for the rationale).

Changed in version 3. 7. For multicast IPv6 address, first item of address does not contain

>>> 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---')]
0 part anymore. In order to get full IPv6 address use .

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

Receive normal data (up to bufsize bytes) and ancillary data from the socket. The ancbufsize argument sets the size in bytes of the internal buffer used to receive the ancillary data; it defaults to 0, meaning that no ancillary data will be received. Appropriate buffer sizes for ancillary data can be calculated using or , and items which do not fit into the buffer might be truncated or discarded. The flags argument defaults to 0 and has the same meaning as for

The return value is a 4-tuple.

>>> 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---')]
19. The data item is a object holding the non-ancillary data received. The ancdata item is a list of zero or more tuples
>>> 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---')]
21 representing the ancillary data (control messages) received. cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively, and cmsg_data is a object holding the associated data. The msg_flags item is the bitwise OR of various flags indicating conditions on the received message; see your system documentation for details. If the receiving socket is unconnected, address is the address of the sending socket, if available; otherwise, its value is unspecified

On some systems, and can be used to pass file descriptors between processes over an socket. When this facility is used (it is often restricted to sockets), will return, in its ancillary data, items of the form

>>> 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---')]
28, where fds is a object representing the new file descriptors as a binary array of the native C int type. If raises an exception after the system call returns, it will first attempt to close any file descriptors received via this mechanism.

Some systems do not indicate the truncated length of ancillary data items which have been only partially received. If an item appears to extend beyond the end of the buffer, will issue a , and will return the part of it which is inside the buffer provided it has not been truncated before the start of its associated data

On systems which support the

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)
49 mechanism, the following function will receive up to maxfds file descriptors, returning the message data and a list containing the descriptors (while ignoring unexpected conditions such as unrelated control messages being received). See also

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

Mới trong phiên bản 3. 3

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an exception (see PEP 475 for the rationale).

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

Receive normal data and ancillary data from the socket, behaving as would, but scatter the non-ancillary data into a series of buffers instead of returning a new bytes object. The buffers argument must be an iterable of objects that export writable buffers (e. g. objects); these will be filled with successive chunks of the non-ancillary data until it has all been written or there are no more buffers. The operating system may set a limit ( value

>>> 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---')]
39) on the number of buffers that can be used. Các đối số ancbufsize và flags có cùng ý nghĩa như đối với

The return value is a 4-tuple.

>>> 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---')]
41, trong đó nbytes là tổng số byte dữ liệu không phụ trợ được ghi vào bộ đệm và ancdata, msg_flags và địa chỉ giống như đối với

Ví dụ

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

Mới trong phiên bản 3. 3

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

Receive data from the socket, writing it into buffer instead of creating a new bytestring. The return value is a pair

>>> 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---')]
43 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. )

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

socket. send(bytes[ , 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 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 topic, consult the

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an exception (see PEP 475 for the rationale).

socket. sendall(bytes[ , 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 above. Unlike , this method continues to send data from bytes until either all data has been sent or an error occurs.

>>> 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))]
30 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

Changed in version 3. 5. The socket timeout is no more reset each time data is sent successfully. The socket timeout is now the maximum total duration to send all data.

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an exception (see PEP 475 for the rationale).

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

Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address. The optional flags argument has the same meaning as for above. Return the number of bytes sent. (The format of address depends on the address family — see above. )

Raises an

>>> 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---')]
51 with arguments
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)
91,
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)
61

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an exception (see PEP 475 for the rationale).

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

Send normal and ancillary data to the socket, gathering the non-ancillary data from a series of buffers and concatenating it into a single message. The buffers argument specifies the non-ancillary data as an iterable of (e. g. objects); the operating system may set a limit ( value

>>> 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---')]
39) on the number of buffers that can be used. The ancdata argument specifies the ancillary data (control messages) as an iterable of zero or more tuples
>>> 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---')]
21, where cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively, and cmsg_data is a bytes-like object holding the associated data. Note that some systems (in particular, systems without ) might support sending only one control message per call. The flags argument defaults to 0 and has the same meaning as for . If address is supplied and not
>>> 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))]
30, it sets a destination address for the message. The return value is the number of bytes of non-ancillary data sent

The following function sends the list of file descriptors fds over an socket, on systems which support the

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)
49 mechanism. See also

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

Raises an

>>> 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---')]
65 with arguments
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)
91,
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)
61

Mới trong phiên bản 3. 3

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an exception (see PEP 475 for the rationale).

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

Specialized version of for socket. Set mode, IV, AEAD associated data length and flags for socket

Linux >= 2. 6. 38

Mới trong phiên bản 3. 6

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

Send a file until EOF is reached by using high-performance and return the total number of bytes which were sent. file must be a regular file object opened in binary mode. If is not available (e. g. Windows) hoặc tệp không phải là tệp thông thường sẽ được sử dụng để thay thế. offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is updated on return or also in case of error in which case can be used to figure out the number of bytes which were sent. The socket must be of type. Non-blocking sockets are not supported

Mới trong phiên bản 3. 5

socket. set_inheritable(inheritable)

Set the of the socket’s file descriptor or socket’s handle

Mới trong phiên bản 3. 4

socket. setblocking(flag)

Set blocking or non-blocking mode of the socket. if flag is false, the socket is set to non-blocking, else to blocking mode

This method is a shorthand for certain calls

  • >>> 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---')]
    
    78 is equivalent to
    >>> 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---')]
    
    79

  • >>> 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---')]
    
    80 is equivalent to
    >>> 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---')]
    
    81

Changed in version 3. 7. The method no longer applies flag on .

socket. settimeout(value)

Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or

>>> 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))]
30. If a non-zero value is given, subsequent socket operations will raise a 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
>>> 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))]
30 is given, the socket is put in blocking mode

For further information, please consult the

Changed in version 3. 7. The method no longer toggles flag on .

socket. setsockopt(level , optname , value. )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 the module (

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)
87 etc. ). The value can be an integer,
>>> 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))]
30 or a 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 for a way to encode C structures as bytestrings). When value is set to
>>> 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))]
30, optlen argument is required. It’s equivalent to call
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)
44 C function with
>>> 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---')]
95 and
>>> 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---')]
96

Đã thay đổi trong phiên bản 3. 5. Có thể ghi hiện được chấp nhận.

Đã thay đổi trong phiên bản 3. 6. setsockopt(level, optname, None, optlen. int) đã thêm biểu mẫu.

không phải WASI

ổ cắm. tắt(cách thức)

Tắt một hoặc cả hai nửa kết nối. Nếu thế nào là

>>> 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---')]
97, việc nhận thêm không được phép. Nếu thế nào là
>>> 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---')]
98, việc gửi thêm sẽ không được phép. Nếu thế nào là
>>> 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---')]
99, việc gửi và nhận tiếp theo không được phép

không phải WASI

ổ cắm. chia sẻ(process_id)

Sao chép một socket và chuẩn bị chia sẻ nó với một process mục tiêu. Quá trình đích phải được cung cấp với process_id. Sau đó, đối tượng byte kết quả có thể được chuyển đến quy trình đích bằng cách sử dụng một số hình thức giao tiếp giữa các quy trình và ổ cắm có thể được tạo lại ở đó bằng cách sử dụng. Khi phương thức này đã được gọi, có thể đóng socket một cách an toàn vì hệ điều hành đã sao chép nó cho tiến trình đích

các cửa sổ

Mới trong phiên bản 3. 3

Lưu ý rằng không có phương pháp

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)
9 hoặc
>>> 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))]
0;

Các đối tượng ổ cắm cũng có các thuộc tính (chỉ đọc) này tương ứng với các giá trị được cung cấp cho hàm tạo

ổ cắm. gia đình

Gia đình ổ cắm

socket. type

The socket type

socket. proto

The socket protocol

Notes on socket timeouts

A socket object can be in one of three modes. blocking, non-blocking, or timeout. Sockets are by default always created in blocking mode, but this can be changed by calling

  • 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. functions from the can be used to know when and whether a socket is available for reading or writing

  • In timeout mode, operations fail if they cannot be completed within the timeout specified for the socket (they raise a exception) or if the system returns an error

Ghi chú

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 of a socket

Timeouts and the import socket, array def send_fds(sock, msg, fds): return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))]) 10 method

The operation is also subject to the timeout setting, and in general it is recommended to call before calling or pass a timeout parameter to . However, the system network stack may also return a connection timeout error of its own regardless of any Python socket timeout setting

Timeouts and the import socket, array def send_fds(sock, msg, fds): return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))]) 15 method

If is not , sockets returned by the method inherit that timeout. Otherwise, the behaviour depends on settings of the listening socket

  • if the listening socket is in blocking mode or in timeout mode, the socket returned by is in blocking mode;

  • if the listening socket is in non-blocking mode, whether the socket returned by is in blocking or non-blocking mode is operating system-dependent. If you want to ensure cross-platform behaviour, it is recommended you manually override this setting

Example

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

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)
8, , , (possibly repeating the to service more than one client), while a client only needs the sequence
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)
8, . Also note that the server does not / on the socket it is listening on but on the new socket returned by

The first two examples support IPv4 only

# 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 the all 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))

The next 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

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)
0

The next example shows how to use the socket interface to communicate to a CAN network using the raw socket protocol. To use CAN with the broadcast manager protocol instead, open a socket with

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)
1

After binding (

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)
83) or connecting () the socket, you can use the , and the operations (and their counterparts) on the socket object as usual

This last example might require special privileges

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)
2

Running an example several times with too small delay between executions, could lead to this error

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)
3

This is because the previous execution has left the socket in a

import socket, array

def send_fds(sock, msg, fds):
    return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
35 state, and can’t be immediately reused

There is a flag to set, in order to prevent this,

import socket, array

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

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)
4

the

>>> 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))]
21 flag tells the kernel to reuse a local socket in
import socket, array

def send_fds(sock, msg, fds):
    return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
35 state, without waiting for its natural timeout to expire

Xem thêm

For an introduction to socket programming (in C), see the following papers

  • An Introductory 4. 3BSD Interprocess Communication Tutorial, by Stuart Sechrest

  • 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. Đối với Unix, hãy tham khảo các trang hướng dẫn; . Đối với API sẵn sàng cho IPv6, người đọc có thể muốn tham khảo RFC 3493 có tiêu đề Tiện ích mở rộng giao diện ổ cắm cơ bản cho IPv6