socket

TCP, UDP and RAW socket support

Create TCP, UDP and RAW sockets for communicating over the Internet.

class socket.socket(family: int, type: int, proto: int)
bind(self, address: tuple)

Bind a socket to an address

Parameters

address (~tuple) – tuple of (remote_address, remote_port)

listen(self, backlog: int)

Set socket to listen for incoming connections

Parameters

backlog (~int) – length of backlog queue for waiting connetions

accept(self)

Accept a connection on a listening socket of type SOCK_STREAM, creating a new socket of type SOCK_STREAM. Returns a tuple of (new_socket, remote_address)

connect(self, address: tuple)

Connect a socket to a remote address

Parameters

address (~tuple) – tuple of (remote_address, remote_port)

send(self, bytes: bytes)

Send some bytes to the connected remote address. Suits sockets of type SOCK_STREAM

Parameters

bytes (~bytes) – some bytes to send

recv_into(self, buffer: bytearray, bufsize: int)

Reads some bytes from the connected remote address, writing into the provided buffer. If bufsize <= len(buffer) is given, a maximum of bufsize bytes will be read into the buffer. If no valid value is given for bufsize, the default is the length of the given buffer.

Suits sockets of type SOCK_STREAM Returns an int of number of bytes read.

Parameters
  • buffer (bytearray) – buffer to receive into

  • bufsize (int) – optionally, a maximum number of bytes to read.

recv(self, bufsize: int)

Reads some bytes from the connected remote address. Suits sockets of type SOCK_STREAM Returns a bytes() of length <= bufsize

Parameters

bufsize (~int) – maximum number of bytes to receive

sendto(self, bytes: bytes, address: tuple)

Send some bytes to a specific address. Suits sockets of type SOCK_DGRAM

Parameters
  • bytes (~bytes) – some bytes to send

  • address (~tuple) – tuple of (remote_address, remote_port)

recvfrom(self, bufsize: int)

Reads some bytes from the connected remote address. Suits sockets of type SOCK_STREAM

Returns a tuple containing * a bytes() of length <= bufsize * a remote_address, which is a tuple of ip address and port number

Parameters

bufsize (~int) – maximum number of bytes to receive

setsockopt(self, level: Any, optname: Any, value: Any)

Sets socket options

settimeout(self, value: int)

Set the timeout value for this socket.

Parameters

value (~int) – timeout in seconds. 0 means non-blocking. None means block indefinitely.

setblocking(self, flag: bool)

Set the blocking behaviour of this socket.

Parameters

flag (~bool) – False means non-blocking, True means block indefinitely.

socket.getaddrinfo(host: Any, port: Any) → Any

Gets the address information for a hostname and port

Returns the appropriate family, socket type, socket protocol and address information to call socket.socket() and socket.connect() with, as a tuple.