socket — TCP, UDP and RAW socket support

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

class socket.socket(family, type, proto, ...)

Create a new socket

Parameters:
  • family (~int) – AF_INET or AF_INET6
  • type (~int) – SOCK_STREAM, SOCK_DGRAM or SOCK_RAW
  • proto (~int) – IPPROTO_TCP, IPPROTO_UDP or IPPROTO_RAW (ignored)
socket.bind(address)

Bind a socket to an address

Parameters:address (~tuple) – tuple of (remote_address, remote_port)
socket.listen(backlog)

Set socket to listen for incoming connections

Parameters:backlog (~int) – length of backlog queue for waiting connetions
socket.accept()

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)

socket.connect(address)

Connect a socket to a remote address

Parameters:address (~tuple) – tuple of (remote_address, remote_port)
socket.send(bytes)

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

Parameters:bytes (~bytes) – some bytes to send
socket.recv(bufsize)

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
socket.sendto(bytes, address)

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)
socket.recvfrom(bufsize)

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

Sets socket options

socket.settimeout(value)

Set the timeout value for this socket.

Parameters:value (~int) – timeout in seconds. 0 means non-blocking. None means block indefinitely.
socket.setblocking(flag)

Set the blocking behaviour of this socket.

Parameters:flag (~bool) – False means non-blocking, True means block indefinitely.
socket.getaddrinfo(host, port)

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.