This module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, MacOS, OS/2, and probably additional platforms. Show
Table of Contents
Table of Contents
Note Some behavior may be platform dependent, since calls are made to the operating system socket APIs. The Python interface is a straightforward transliteration of the Unix system call and library interface for sockets to Python’s object-oriented style: the See also Modulesocketserver Classes that simplify writing network servers.Module ssl A TLS/SSL wrapper for socket objects.17.2.1. Socket families¶Depending on the system and the build options, various socket families are supported by this module. Socket addresses are represented as follows:
For IPv4 addresses, two special
forms are accepted instead of a host address: the empty string represents If you use a hostname in the host portion of IPv4/v6 socket address, the program may show a nondeterministic behavior, as Python uses the first address returned from the DNS resolution. The socket address will be resolved differently into an actual IPv4/v6 address, depending on the results from DNS resolution and/or the host configuration. For deterministic behavior use a numeric address in host portion. All errors raise exceptions. The normal exceptions for invalid argument types and out-of-memory conditions can be raised; errors related to socket or address semantics raise Non-blocking mode is supported through 17.2.2. Module contents¶The module socket. error ¶A subclass of See also The socket. herror ¶A subclass of socket. gaierror ¶A subclass of socket. timeout ¶A subclass of socket. AF_UNIX ¶ socket. AF_INET ¶ socket. AF_INET6 ¶These constants represent the address (and protocol) families, used for the first argument to socket. SOCK_STREAM ¶ socket. SOCK_DGRAM ¶ socket. SOCK_RAW ¶
socket. SOCK_RDM ¶ socket. SOCK_SEQPACKET ¶These constants represent the socket types, used for the second argument to socket. SOCK_CLOEXEC ¶ socket. SOCK_NONBLOCK ¶These two constants, if defined, can be combined with the socket types and allow you to set some flags atomically (thus avoiding possible race conditions and the need for separate calls). Availability: Linux >= 2.6.27. New in version 3.2: New in version 3.2. SO_* socket. SOMAXCONN ¶ MSG_* SOL_* IPPROTO_* IPPORT_* INADDR_* IP_* IPV6_* EAI_* AI_* NI_* TCP_* Many constants of these forms, documented in the Unix documentation on sockets and/or the IP protocol, are also defined in the socket module. They are generally used in arguments to the SIO_* RCVALL_* Constants for Windows’ WSAIoctl(). The constants are used as arguments to the TIPC_* TIPC related constants, matching the ones exported by the C socket API. See the TIPC documentation for more information. socket. has_ipv6 ¶This constant contains a boolean value which indicates if IPv6 is supported on this platform. socket. create_connection (address[, timeout[, source_address]])¶Convenience function. Connect to address (a 2-tuple If supplied, source_address must be a
2-tuple Changed in version 3.2: Changed in version 3.2: source_address was added. Changed in version 3.2: Changed in version 3.2: support for the socket. getaddrinfo (host, port, family=0, type=0, proto=0,
flags=0)¶Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. host is a domain name, a string representation of an IPv4/v6 address or The family, type and proto arguments can be optionally
specified in order to narrow the list of addresses returned. Passing zero as a value for each of these arguments selects the full range of results. The flags argument can be one or several of the The function returns a list of 5-tuples with the following structure:
In these tuples,
family, type, proto are all integers and are meant to be passed to the The following example fetches address information
for a hypothetical TCP connection to >>> socket.getaddrinfo("www.python.org", 80, proto=socket.SOL_TCP) [(2, 1, 6, '', ('82.94.164.162', 80)), (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))] Changed in version 3.2: Changed in version 3.2: parameters can now be passed as single keyword arguments. socket. getfqdn ([name])¶Return a fully qualified domain name for name. If name is omitted or empty, it is interpreted as the local host. To find the fully qualified name,
the hostname returned by socket. gethostbyname (hostname)¶Translate a host name to IPv4 address format. The IPv4 address is returned as a string, such as socket. gethostbyname_ex (hostname)¶Translate a host name to IPv4 address format, extended interface. Return a triple socket. gethostname ()¶Return a string containing the hostname of the machine where the Python interpreter is currently executing. If you want to know the current machine’s IP address, you may want to use Note: socket. gethostbyaddr (ip_address)¶Return a triple socket. getnameinfo (sockaddr, flags)¶Translate a socket address sockaddr into a 2-tuple socket. getprotobyname (protocolname)¶Translate an Internet protocol name (for example, socket. getservbyname (servicename[,
protocolname])¶Translate an Internet service name and protocol name to a port number for that service. The optional protocol name, if given, should be socket. getservbyport (port[, protocolname])¶Translate an Internet port number and protocol name to a service name for that service. The optional protocol name, if given, should be socket. socket ([family[, type[, proto]]])¶Create a new socket using the given address family, socket type and protocol number. The address family should be socket. socketpair ([family[, type[, proto]]])¶Build a pair of connected socket objects using the given address family, socket type, and protocol number. Address family, socket type, and protocol number are as for the Changed in version 3.2: Changed in version 3.2: The returned socket objects now support the whole socket API, rather than a subset. socket. fromfd (fd, family, type[, proto])¶Duplicate the file descriptor fd (an integer as returned by a file object’s socket. ntohl (x)¶Convert 32-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. socket. ntohs (x)¶Convert 16-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. socket. htonl (x)¶Convert 32-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. socket. htons (x)¶Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. socket. inet_aton (ip_string)¶Convert an IPv4 address from
dotted-quad string format (for example, ‘123.45.67.89’) to 32-bit packed binary format, as a bytes object four characters in length. This is useful when conversing with a program that uses the standard C library and needs objects of type
If the IPv4 address string passed to this function is invalid,
socket. inet_ntoa (packed_ip)¶Convert a 32-bit packed IPv4 address (a bytes object four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when
conversing with a program that uses the standard C library and needs objects of type If the byte sequence passed to this function is not exactly 4 bytes in length, socket. inet_pton (address_family, ip_string)¶Convert an IP address from
its family-specific string format to a packed, binary format. Supported values for address_family are currently Availability: Unix (maybe not all platforms). socket. inet_ntop (address_family, packed_ip)¶Convert a packed IP address (a bytes object of some number of characters) to its standard, family-specific string representation (for example, Supported values for address_family are currently Availability: Unix (maybe not all platforms). socket. getdefaulttimeout ()¶Return the default timeout in seconds (float) for new socket objects. A value of 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. SocketType ¶This is a Python type object that represents the socket object type. It is the same as 17.2.3. Socket Objects¶Socket objects have the
following methods. Except for socket. accept ()¶Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair 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.) socket. close ()¶Close the socket. All future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected. Note
socket. connect (address)¶Connect to a remote socket at address. (The format of address depends on the address family — see above.) socket. connect_ex (address)¶Like socket. detach ()¶Put the socket object into closed state without actually closing the underlying file descriptor. The file descriptor is returned, and can be reused for other purposes. New in version 3.2: New in version 3.2. socket. fileno ()¶Return the socket’s file descriptor (a small integer). 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 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 ( socket. gettimeout ()¶Return the timeout in seconds (float) associated with socket operations, or socket. ioctl (control, option)¶
The On other platforms, the generic socket. listen (backlog)¶Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 0; the maximum value is system-dependent (usually 5), the minimum value is forced to 0. socket. makefile (mode='r', buffering=None, *, encoding=None, errors=None, newline=None)¶Return a file object associated with the socket. The exact returned type depends on the arguments given to Closing the file object won’t close the socket unless there are no remaining references to the socket. The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer may end up in a inconsistent state if a timeout occurs. Note On Windows, the file-like object created by 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. Note For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096. socket. recvfrom (bufsize[, flags])¶Receive data from the
socket. The return value is a pair 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 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 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 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 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
socket. settimeout (value)¶Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or For further information, please consult the notes on socket timeouts. socket. setsockopt (level, optname, value)¶Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket. shutdown (how)¶Shut down one or both halves of the connection. If how is Note that there are no methods Socket objects also have these (read-only) attributes that correspond to the values given to the socket. family ¶The socket family. socket. type ¶The socket type. socket. proto ¶The socket protocol. 17.2.4. 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
Note 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 17.2.4.1. Timeouts and the connect method¶The 17.2.4.2. Timeouts and the accept method¶If
17.2.5. 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 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 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print('Connected by', addr) while True: data = conn.recv(1024) if not data: break conn.send(data) conn.close() # Echo client program import socket HOST = 'daring.cwi.nl' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send(b'Hello, world') data = s.recv(1024) s.close() 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 socket.error as msg: s = None continue try: s.bind(sa) s.listen(1) except socket.error as msg: s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) conn, addr = s.accept() print('Connected by', addr) while True: data = conn.recv(1024) if not data: break conn.send(data) conn.close() # Echo client program import socket import sys HOST = 'daring.cwi.nl' # The remote host PORT = 50007 # The same port as used by the server s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except socket.error as msg: s = None continue try: s.connect(sa) except socket.error as msg: s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) s.send(b'Hello, world') data = s.recv(1024) s.close() print('Received', repr(data)) The last example shows how to write a very simple network sniffer with raw sockets on Windows. The example requires administrator privileges to modify the interface: import socket # the public network interface HOST = socket.gethostbyname(socket.gethostname()) # create a raw socket and bind it to the public interface s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) s.bind((HOST, 0)) # Include IP headers s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # receive all packages s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) # receive a package print(s.recvfrom(65565)) # disabled promiscuous mode s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) Running an example several times with too small delay between executions, could lead to this error: socket.error: [Errno 98] Address already in use This is because the previous execution has left the socket in a There is a s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) the See also For an introduction to socket programming (in C), see the following papers:
both in the UNIX Programmer’s Manual, Supplementary Documents 1 (sections PS1:7 and PS1:8). The platform-specific reference material for the various socket-related system calls are also a valuable source of information on the details of socket semantics. For Unix, refer to the manual pages; for Windows, see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may want to refer to RFC 3493 titled Basic Socket Interface Extensions for IPv6. What is the default socket timeout Python?A new Python socket by default doesn't have a timeout. Its timeout defaults to None. Not setting the connection timeout parameter can result in blocking socket mode. In blocking mode, operations block until complete or the system returns an error. What is the default socket timeout?timeout - the socket timeout value passed to the Socket. setSoTimeout() method. The default on the server side is 60000 milliseconds. How do I increase the socket timeout in Python?Then, you can get the socket timeout value by calling gettimeout() and alter the value by calling the settimeout() method. The timeout value passed to the settimeout() method can be in seconds (non-negative float) or None . This method is used for manipulating the blocking-socket operations. How do I set a socket timeout?Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code: String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket. setSoTimeout(10*1000); |