Python except socket error

Source code: Lib/socket.py

Source code: Lib/socket.py


This module provides access to the BSD socket interface. It is available on
all modern Unix systems, Windows, MacOS, and probably additional platforms.

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
socket() function returns a socket object whose methods implement
the various socket system calls. Parameter types are somewhat higher-level than
in the C interface: as with read() and write() operations on Python
files, buffer allocation on receive operations is automatic, and buffer length
is implicit on send operations.

See also

Module socketserver
Classes that simplify writing network servers.
Module ssl
A TLS/SSL wrapper for socket objects.

18.1.1. Socket families¶

Depending on the system and the build options, various socket families
are supported by this module.

The address format required by a particular socket object is automatically
selected based on the address family specified when the socket object was
created. Socket addresses are represented as follows:

  • The address of an AF_UNIX socket bound to a file system node
    is represented as a string, using the file system encoding and the
    'surrogateescape' error handler (see PEP 383). An address in
    Linux’s abstract namespace is returned as a bytes-like object with
    an initial null byte; note that sockets in this namespace can
    communicate with normal file system sockets, so programs intended to
    run on Linux may need to deal with both types of address. A string or
    bytes-like object can be used for either type of address when
    passing it as an argument.

    Changed in version 3.3: Previously, AF_UNIX socket paths were assumed to use UTF-8
    encoding.

  • A pair (host, port) is used for the AF_INET address family,
    where host is a string representing either a hostname in Internet domain
    notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5',
    and port is an integer.

  • For AF_INET6 address family, a four-tuple (host, port, flowinfo,
    scopeid)
    is used, where flowinfo and scopeid represent the sin6_flowinfo
    and sin6_scope_id members in struct sockaddr_in6 in C. For
    socket module methods, flowinfo and scopeid can be omitted just for
    backward compatibility. Note, however, omission of scopeid can cause problems
    in manipulating scoped IPv6 addresses.

  • AF_NETLINK sockets are represented as pairs (pid, groups).

  • Linux-only support for TIPC is available using the AF_TIPC
    address family. TIPC is an open, non-IP based networked protocol designed
    for use in clustered computer environments. Addresses are represented by a
    tuple, and the fields depend on the address type. The general tuple form is
    (addr_type, v1, v2, v3 [, scope]), where:

    • addr_type is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME,
      or TIPC_ADDR_ID.

    • scope is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and
      TIPC_NODE_SCOPE.

    • If addr_type is TIPC_ADDR_NAME, then v1 is the server type, v2 is
      the port identifier, and v3 should be 0.

      If addr_type is TIPC_ADDR_NAMESEQ, then v1 is the server type, v2
      is the lower port number, and v3 is the upper port number.

      If addr_type is TIPC_ADDR_ID, then v1 is the node, v2 is the
      reference, and v3 should be set to 0.

  • A tuple (interface, ) is used for the AF_CAN address family,
    where interface is a string representing a network interface name like
    'can0'. The network interface name '' can be used to receive packets
    from all network interfaces of this family.

    • CAN_ISOTP protocol require a tuple (interface, rx_addr, tx_addr)
      where both additional parameters are unsigned long integer that represent a
      CAN identifier (standard or extended).
  • A string or a tuple (id, unit) is used for the SYSPROTO_CONTROL
    protocol of the PF_SYSTEM family. The string is the name of a
    kernel control using a dynamically-assigned ID. The tuple can be used if ID
    and unit number of the kernel control are known or if a registered ID is
    used.

    New in version 3.3.

  • AF_BLUETOOTH supports the following protocols and address
    formats:

    • BTPROTO_L2CAP accepts (bdaddr, psm) where bdaddr is
      the Bluetooth address as a string and psm is an integer.

    • BTPROTO_RFCOMM accepts (bdaddr, channel) where bdaddr
      is the Bluetooth address as a string and channel is an integer.

    • BTPROTO_HCI accepts (device_id,) where device_id is
      either an integer or a string with the Bluetooth address of the
      interface. (This depends on your OS; NetBSD and DragonFlyBSD expect
      a Bluetooth address while everything else expects an integer.)

      Changed in version 3.2: NetBSD and DragonFlyBSD support added.

    • BTPROTO_SCO accepts bdaddr where bdaddr is a
      bytes object containing the Bluetooth address in a
      string format. (ex. b'12:23:34:45:56:67') This protocol is not
      supported under FreeBSD.

  • AF_ALG is a Linux-only socket based interface to Kernel
    cryptography. An algorithm socket is configured with a tuple of two to four
    elements (type, name [, feat [, mask]]), where:

    • type is the algorithm type as string, e.g. aead, hash,
      skcipher or rng.
    • name is the algorithm name and operation mode as string, e.g.
      sha256, hmac(sha256), cbc(aes) or drbg_nopr_ctr_aes256.
    • feat and mask are unsigned 32bit integers.

    Availability Linux 2.6.38, some algorithm types require more recent Kernels.

    New in version 3.6.

  • AF_VSOCK allows communication between virtual machines and
    their hosts. The sockets are represented as a (CID, port) tuple
    where the context ID or CID and port are integers.

    Availability: Linux >= 4.8 QEMU >= 2.8 ESX >= 4.0 ESX Workstation >= 6.5

    New in version 3.7.

  • Certain other address families (AF_PACKET, AF_CAN)
    support specific representations.

For IPv4 addresses, two special forms are accepted instead of a host address:
the empty string represents INADDR_ANY, and the string
'<broadcast>' represents INADDR_BROADCAST. This behavior is not
compatible with IPv6, therefore, you may want to avoid these if you intend
to support IPv6 with your Python programs.

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; starting from Python 3.3, errors
related to socket or address semantics raise OSError or one of its
subclasses (they used to raise socket.error).

Non-blocking mode is supported through setblocking(). A
generalization of this based on timeouts is supported through
settimeout().

18.1.2. Module contents¶

The module socket exports the following elements.

18.1.2.1. Exceptions¶

exception socket.error

A deprecated alias of OSError.

Changed in version 3.3: Following PEP 3151, this class was made an alias of OSError.

exception socket.herror

A subclass of OSError, this exception is raised for
address-related errors, i.e. for functions that use h_errno in the POSIX
C API, including gethostbyname_ex() and gethostbyaddr().
The accompanying value is a pair (h_errno, string) representing an
error returned by a library call. h_errno is a numeric value, while
string represents the description of h_errno, as returned by the
hstrerror() C function.

Changed in version 3.3: This class was made a subclass of OSError.

exception socket.gaierror

A subclass of OSError, this exception is raised for
address-related errors by getaddrinfo() and getnameinfo().
The accompanying value is a pair (error, string) representing an error
returned by a library call. string represents the description of
error, as returned by the gai_strerror() C function. The
numeric error value will match one of the EAI_* constants
defined in this module.

Changed in version 3.3: This class was made a subclass of OSError.

exception socket.timeout

A subclass of OSError, this exception is raised when a timeout
occurs on a socket which has had timeouts enabled via a prior call to
settimeout() (or implicitly through
setdefaulttimeout()). The accompanying value is a string
whose value is currently always “timed out”.

Changed in version 3.3: This class was made a subclass of OSError.

18.1.2.2. Constants¶

The AF_* and SOCK_* constants are now AddressFamily and
SocketKind IntEnum collections.

New in version 3.4.

socket.AF_UNIX
socket.AF_INET
socket.AF_INET6

These constants represent the address (and protocol) families, used for the
first argument to socket(). If the AF_UNIX constant is not
defined then this protocol is unsupported. More constants may be available
depending on the system.

socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET

These constants represent the socket types, used for the second argument to
socket(). More constants may be available depending on the system.
(Only SOCK_STREAM and SOCK_DGRAM appear to be generally
useful.)

socket.SOCK_CLOEXEC
socket.SOCK_NONBLOCK

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.

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

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

Changed in version 3.6: SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC, SO_PASSSEC,
TCP_USER_TIMEOUT, TCP_CONGESTION were added.

Changed in version 3.7: TCP_NOTSENT_LOWAT was added.

socket.AF_CAN
socket.PF_CAN
SOL_CAN_*
CAN_*

Many constants of these forms, documented in the Linux documentation, are
also defined in the socket module.

Availability: Linux >= 2.6.25.

New in version 3.3.

socket.CAN_BCM
CAN_BCM_*

CAN_BCM, in the CAN protocol family, is the broadcast manager (BCM) protocol.
Broadcast manager constants, documented in the Linux documentation, are also
defined in the socket module.

Availability: Linux >= 2.6.25.

New in version 3.4.

socket.CAN_RAW_FD_FRAMES

Enables CAN FD support in a CAN_RAW socket. This is disabled by default.
This allows your application to send both CAN and CAN FD frames; however,
you one must accept both CAN and CAN FD frames when reading from the socket.

This constant is documented in the Linux documentation.

Availability: Linux >= 3.6.

New in version 3.5.

socket.CAN_ISOTP

CAN_ISOTP, in the CAN protocol family, is the ISO-TP (ISO 15765-2) protocol.
ISO-TP constants, documented in the Linux documentation.

Availability: Linux >= 2.6.25

New in version 3.7.

socket.AF_RDS
socket.PF_RDS
socket.SOL_RDS
RDS_*

Many constants of these forms, documented in the Linux documentation, are
also defined in the socket module.

Availability: Linux >= 2.6.30.

New in version 3.3.

socket.SIO_RCVALL
socket.SIO_KEEPALIVE_VALS
socket.SIO_LOOPBACK_FAST_PATH
RCVALL_*

Constants for Windows’ WSAIoctl(). The constants are used as arguments to the
ioctl() method of socket objects.

Changed in version 3.6: SIO_LOOPBACK_FAST_PATH was added.

TIPC_*

TIPC related constants, matching the ones exported by the C socket API. See
the TIPC documentation for more information.

socket.AF_ALG
socket.SOL_ALG
ALG_*

Constants for Linux Kernel cryptography.

Availability: Linux >= 2.6.38.

New in version 3.6.

socket.AF_VSOCK
socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID
VMADDR*
SO_VM*

Constants for Linux host/guest communication.

Availability: Linux >= 4.8.

New in version 3.7.

socket.AF_LINK

Availability: BSD, OSX.

New in version 3.4.

socket.has_ipv6

This constant contains a boolean value which indicates if IPv6 is supported on
this platform.

socket.BDADDR_ANY
socket.BDADDR_LOCAL

These are string constants containing Bluetooth addresses with special
meanings. For example, BDADDR_ANY can be used to indicate
any address when specifying the binding socket with
BTPROTO_RFCOMM.

socket.HCI_FILTER
socket.HCI_TIME_STAMP
socket.HCI_DATA_DIR

For use with BTPROTO_HCI. HCI_FILTER is not
available for NetBSD or DragonFlyBSD. HCI_TIME_STAMP and
HCI_DATA_DIR are not available for FreeBSD, NetBSD, or
DragonFlyBSD.

18.1.2.3. Functions¶

18.1.2.3.1. Creating sockets¶

The following functions all create socket objects.

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

Create a new socket using the given address family, socket type and protocol
number. The address family should be AF_INET (the default),
AF_INET6, AF_UNIX, AF_CAN or AF_RDS. The
socket type should be SOCK_STREAM (the default),
SOCK_DGRAM, SOCK_RAW or perhaps one of the other SOCK_
constants. The protocol number is usually zero and may be omitted or in the
case where the address family is AF_CAN the protocol should be one
of CAN_RAW, CAN_BCM or CAN_ISOTP. If fileno is specified, the other
arguments are ignored, causing the socket with the specified file descriptor
to return. Unlike socket.fromfd(), fileno will return the same
socket and not a duplicate. This may help close a detached socket using
socket.close().

The newly created socket is non-inheritable.

Changed in version 3.3: The AF_CAN family was added.
The AF_RDS family was added.

Changed in version 3.4: The CAN_BCM protocol was added.

Changed in version 3.4: The returned socket is now non-inheritable.

Changed in version 3.7: The CAN_ISOTP protocol was added.

socket.socketpair([family[, type[, proto]]])

Build a pair of connected socket objects using the given address family, socket
type, and protocol number. Address family, socket type, and protocol number are
as for the socket() function above. The default family is AF_UNIX
if defined on the platform; otherwise, the default is AF_INET.

The newly created sockets are non-inheritable.

Changed in version 3.2: The returned socket objects now support the whole socket API, rather
than a subset.

Changed in version 3.4: The returned sockets are now non-inheritable.

Changed in version 3.5: Windows support added.

socket.create_connection(address[, timeout[, source_address]])

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

Passing the optional timeout parameter will set the timeout on the
socket instance before attempting to connect. If no timeout is
supplied, the global default timeout setting returned by
getdefaulttimeout() is used.

If supplied, source_address must be a 2-tuple (host, port) for the
socket to bind to as its source address before connecting. If host or port
are ‘’ or 0 respectively the OS default behavior will be used.

Changed in version 3.2: source_address was added.

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

Duplicate the file descriptor fd (an integer as returned by a file object’s
fileno() method) and build a socket object from the result. Address
family, socket type and protocol number are as for the socket() function
above. The file descriptor should refer to a socket, but this is not checked —
subsequent operations on the object may fail if the file descriptor is invalid.
This function is rarely needed, but can be used to get or set socket options on
a socket passed to a program as standard input or output (such as a server
started by the Unix inet daemon). The socket is assumed to be in blocking mode.

The newly created socket is non-inheritable.

Changed in version 3.4: The returned socket is now non-inheritable.

socket.fromshare(data)

Instantiate a socket from data obtained from the socket.share()
method. The socket is assumed to be in blocking mode.

Availability: Windows.

New in version 3.3.

socket.SocketType

This is a Python type object that represents the socket object type. It is the
same as type(socket(...)).

18.1.2.3.2. Other functions¶

The socket module also offers various network-related services:

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 None. port is a string service name such as 'http', a numeric
port number or None. By passing None as the value of host
and port, you can pass NULL to the underlying C API.

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 AI_* constants,
and will influence how results are computed and returned.
For example, AI_NUMERICHOST will disable domain name resolution
and will raise an error if host is a domain name.

The function returns a list of 5-tuples with the following structure:

(family, type, proto, canonname, sockaddr)

In these tuples, family, type, proto are all integers and are
meant to be passed to the socket() function. canonname will be
a string representing the canonical name of the host if
AI_CANONNAME is part of the flags argument; else canonname
will be empty. sockaddr is a tuple describing a socket address, whose
format depends on the returned family (a (address, port) 2-tuple for
AF_INET, a (address, port, flow info, scope id) 4-tuple for
AF_INET6), and is meant to be passed to the socket.connect()
method.

The following example fetches address information for a hypothetical TCP
connection to example.org on port 80 (results may differ on your
system if IPv6 isn’t enabled):

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

Changed in version 3.2: parameters can now be passed using 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 gethostbyaddr() is checked, followed by aliases for the
host, if available. The first name which includes a period is selected. In
case no fully qualified domain name is available, the hostname as returned by
gethostname() is returned.

socket.gethostbyname(hostname)

Translate a host name to IPv4 address format. The IPv4 address is returned as a
string, such as '100.50.200.5'. If the host name is an IPv4 address itself
it is returned unchanged. See gethostbyname_ex() for a more complete
interface. gethostbyname() does not support IPv6 name resolution, and
getaddrinfo() should be used instead for IPv4/v6 dual stack support.

socket.gethostbyname_ex(hostname)

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

socket.gethostname()

Return a string containing the hostname of the machine where the Python
interpreter is currently executing.

Note: gethostname() doesn’t always return the fully qualified domain
name; use getfqdn() for that.

socket.gethostbyaddr(ip_address)

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

socket.getnameinfo(sockaddr, flags)

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

socket.getprotobyname(protocolname)

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

socket.getservbyname(servicename[, protocolname])

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

socket.getservbyport(port[, protocolname])

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

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.

Deprecated since version 3.7: In case x does not fit in 16-bit unsigned integer, but does fit in a
positive C int, it is silently truncated to 16-bit unsigned integer.
This silent truncation feature is deprecated, and will raise an
exception in future versions of Python.

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.

Deprecated since version 3.7: In case x does not fit in 16-bit unsigned integer, but does fit in a
positive C int, it is silently truncated to 16-bit unsigned integer.
This silent truncation feature is deprecated, and will raise an
exception in future versions of Python.

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 struct in_addr, which is the C type
for the 32-bit packed binary this function returns.

inet_aton() also accepts strings with less than three dots; see the
Unix manual page inet(3) for details.

If the IPv4 address string passed to this function is invalid,
OSError will be raised. Note that exactly what is valid depends on
the underlying C implementation of inet_aton().

inet_aton() does not support IPv6, and inet_pton() should be used
instead for IPv4/v6 dual stack support.

socket.inet_ntoa(packed_ip)

Convert a 32-bit packed IPv4 address (a bytes-like object four
bytes in length) to its standard dotted-quad string representation (for example,
‘123.45.67.89’). This is useful when conversing with a program that uses the
standard C library and needs objects of type struct in_addr, 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, OSError will be raised. inet_ntoa() does not
support IPv6, and inet_ntop() should be used instead for IPv4/v6 dual
stack support.

socket.inet_pton(address_family, ip_string)

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

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

Availability: Unix (maybe not all platforms), Windows.

Changed in version 3.4: Windows support added

socket.inet_ntop(address_family, packed_ip)

Convert a packed IP address (a bytes-like object of some number of
bytes) to its standard, family-specific string representation (for
example, '7.10.0.5' or '5aef:2b::8').
inet_ntop() is useful when a library or network protocol returns an
object of type struct in_addr (similar to inet_ntoa()) or
struct in6_addr.

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

Availability: Unix (maybe not all platforms), Windows.

Changed in version 3.4: Windows support added

socket.CMSG_LEN(length)

Return the total length, without trailing padding, of an ancillary
data item with associated data of the given length. This value
can often be used as the buffer size for recvmsg() to
receive a single item of ancillary data, but RFC 3542 requires
portable applications to use CMSG_SPACE() and thus include
space for padding, even when the item will be the last in the
buffer. Raises OverflowError if length is outside the
permissible range of values.

Availability: most Unix platforms, possibly others.

New in version 3.3.

socket.CMSG_SPACE(length)

Return the buffer size needed for recvmsg() 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 CMSG_SPACE()
values for their associated data lengths. Raises
OverflowError 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.

Availability: most Unix platforms, possibly others.

New in version 3.3.

socket.getdefaulttimeout()

Return the default timeout in seconds (float) for new socket objects. A value
of None indicates that new socket objects have no timeout. When the socket
module is first imported, the default is None.

socket.setdefaulttimeout(timeout)

Set the default timeout in seconds (float) for new socket objects. When
the socket module is first imported, the default is None. See
settimeout() for possible values and their respective
meanings.

socket.sethostname(name)

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

Availability: Unix.

New in version 3.3.

socket.if_nameindex()

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

Availability: Unix.

New in version 3.3.

socket.if_nametoindex(if_name)

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

Availability: Unix.

New in version 3.3.

socket.if_indextoname(if_index)

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

Availability: Unix.

New in version 3.3.

18.1.3. Socket Objects¶

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

Changed in version 3.2: Support for the context manager protocol was added. Exiting the
context manager is equivalent to calling close().

socket.accept()

Accept a connection. The socket must be bound to an address and listening for
connections. The return value is a pair (conn, address) 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.

The newly created socket is non-inheritable.

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 InterruptedError 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.)

socket.close()

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

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

Changed in version 3.6: OSError is now raised if an error occurs when the underlying
close() call is made.

Note

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

socket.connect(address)

Connect to a remote socket at address. (The format of address depends on the
address family — see above.)

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

Changed in version 3.5: The method now waits until the connection completes instead of raising an
InterruptedError exception if the connection is interrupted by a
signal, the signal handler doesn’t raise an exception and the socket is
blocking or has a timeout (see the PEP 475 for the rationale).

socket.connect_ex(address)

Like connect(address), but return an error indicator instead of raising an
exception for errors returned by the C-level connect() call (other
problems, such as “host not found,” can still raise exceptions). The error
indicator is 0 if the operation succeeded, otherwise the value of the
errno variable. This is useful to support, for example, asynchronous
connects.

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.

socket.dup()

Duplicate the socket.

The newly created socket is non-inheritable.

Changed in version 3.4: The socket is now non-inheritable.

socket.fileno()

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

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

socket.get_inheritable()

Get the inheritable flag of the socket’s file
descriptor or socket’s handle: True if the socket can be inherited in
child processes, False if it cannot.

New in version 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 (SO_* etc.)
are defined in this module. If buflen is absent, an integer option is assumed
and its integer value is returned by the function. If buflen is present, it
specifies the maximum length of the buffer used to receive the option in, and
this buffer is returned as a bytes object. It is up to the caller to decode the
contents of the buffer (see the optional built-in module struct for a way
to decode C structures encoded as byte strings).

socket.gettimeout()

Return the timeout in seconds (float) associated with socket operations,
or None if no timeout is set. This reflects the last call to
setblocking() or settimeout().

socket.ioctl(control, option)
Platform: Windows

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

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

Currently only the following control codes are supported:
SIO_RCVALL, SIO_KEEPALIVE_VALS, and SIO_LOOPBACK_FAST_PATH.

Changed in version 3.6: SIO_LOOPBACK_FAST_PATH was added.

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.

Changed in version 3.5: The backlog parameter is now optional.

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

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

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 makefile() won’t close the
original socket unless all other file objects have been closed and
socket.close() has been called on the socket object.

Note

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

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.

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 InterruptedError exception (see PEP 475 for the rationale).

socket.recvfrom(bufsize[, flags])

Receive data from the socket. The return value is a pair (bytes, address)
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 InterruptedError exception (see PEP 475 for the rationale).

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
CMSG_SPACE() or CMSG_LEN(), 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
recv().

The return value is a 4-tuple: (data, ancdata, msg_flags,
address)
. The data item is a bytes object holding the
non-ancillary data received. The ancdata item is a list of zero
or more tuples (cmsg_level, cmsg_type, cmsg_data) 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
bytes 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, sendmsg() and recvmsg() can be used to
pass file descriptors between processes over an AF_UNIX
socket. When this facility is used (it is often restricted to
SOCK_STREAM sockets), recvmsg() will return, in its
ancillary data, items of the form (socket.SOL_SOCKET,
socket.SCM_RIGHTS, fds)
, where fds is a bytes object
representing the new file descriptors as a binary array of the
native C int type. If recvmsg() raises an
exception after the system call returns, it will first attempt to
close any file descriptors received via this mechanism.

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, recvmsg() will issue
a RuntimeWarning, 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 SCM_RIGHTS 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 sendmsg().

import socket, array

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

Availability: most Unix platforms, possibly others.

New in version 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 InterruptedError exception (see PEP 475 for the rationale).

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

Receive normal data and ancillary data from the socket, behaving as
recvmsg() 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. bytearray 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 (sysconf() value SC_IOV_MAX)
on the number of buffers that can be used. The ancbufsize and
flags arguments have the same meaning as for recvmsg().

The return value is a 4-tuple: (nbytes, ancdata, msg_flags,
address)
, where nbytes is the total number of bytes of
non-ancillary data written into the buffers, and ancdata,
msg_flags and address are the same as for recvmsg().

Example:

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

Availability: most Unix platforms, possibly others.

New in version 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 (nbytes, address) 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 recv() 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 Socket Programming HOWTO.

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 InterruptedError 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 recv() above.
Unlike send(), this method continues to send data from bytes until
either all data has been sent or an error occurs. None 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 InterruptedError 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 recv() above. Return the number of
bytes sent. (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 InterruptedError 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
bytes-like objects
(e.g. bytes objects); the operating system may set a limit
(sysconf() value SC_IOV_MAX) 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
(cmsg_level, cmsg_type, cmsg_data), 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 CMSG_SPACE())
might support sending only one control message per call. The
flags argument defaults to 0 and has the same meaning as for
send(). If address is supplied and not None, 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 AF_UNIX socket, on systems which support the
SCM_RIGHTS mechanism. See also recvmsg().

import socket, array

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

Availability: most Unix platforms, possibly others.

New in version 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 InterruptedError exception (see PEP 475 for the rationale).

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

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

Availability: Linux >= 2.6.38

New in version 3.6.

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

Send a file until EOF is reached by using high-performance
os.sendfile and return the total number of bytes which were sent.
file must be a regular file object opened in binary mode. If
os.sendfile is not available (e.g. Windows) or file is not a
regular file send() will be used instead. 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
file.tell() can be used to figure out the number of
bytes which were sent. The socket must be of SOCK_STREAM type.
Non-blocking sockets are not supported.

New in version 3.5.

socket.set_inheritable(inheritable)

Set the inheritable flag of the socket’s file
descriptor or socket’s handle.

New in version 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 settimeout() calls:

  • sock.setblocking(True) is equivalent to sock.settimeout(None)
  • sock.setblocking(False) is equivalent to sock.settimeout(0.0)
socket.settimeout(value)

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

For further information, please consult the notes on socket timeouts.

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

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

Changed in version 3.6: setsockopt(level, optname, None, optlen: int) form added.

socket.shutdown(how)

Shut down one or both halves of the connection. If how is SHUT_RD,
further receives are disallowed. If how is SHUT_WR, further sends
are disallowed. If how is SHUT_RDWR, further sends and receives are
disallowed.

Duplicate a socket and prepare it for sharing with a target process. The
target process must be provided with process_id. The resulting bytes object
can then be passed to the target process using some form of interprocess
communication and the socket can be recreated there using fromshare().
Once this method has been called, it is safe to close the socket since
the operating system has already duplicated it for the target process.

Availability: Windows.

New in version 3.3.

Note that there are no methods read() or write(); use
recv() and send() without flags argument instead.

Socket objects also have these (read-only) attributes that correspond to the
values given to the socket constructor.

socket.family

The socket family.

socket.type

The socket type.

socket.proto

The socket protocol.

18.1.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 setdefaulttimeout().

  • 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
    select 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 timeout exception)
    or if the system returns an error.

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 fileno() of a socket.

18.1.4.1. Timeouts and the connect method¶

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

18.1.4.2. Timeouts and the accept method¶

If getdefaulttimeout() is not None, sockets returned by
the accept() 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 accept() is in blocking mode;
  • if the listening socket is in non-blocking mode, whether the socket
    returned by accept() 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.

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

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

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

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:

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

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

This last example might require special privileges:

import socket
import struct


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

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

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

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


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

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

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

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

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

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

OSError: [Errno 98] Address already in use

This is because the previous execution has left the socket in a TIME_WAIT
state, and can’t be immediately reused.

There is a socket flag to set, in order to prevent this,
socket.SO_REUSEADDR:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))

the SO_REUSEADDR flag tells the kernel to reuse a local socket in
TIME_WAIT state, without waiting for its natural timeout to expire.

See also

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

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. 
They are the real backbones behind web browsing. In simpler terms, there is a server and a client. 
Socket programming is started by importing the socket library and making a simple socket. 

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address-family ipv4. The SOCK_STREAM means connection-oriented TCP protocol. 
Now we can connect to a server using this socket.

Connecting to a server: 

Note that if any error occurs during the creation of a socket then a socket. error is thrown and we can only connect to a server by knowing its IP. You can find the IP of the server by using this : 

$ ping www.google.com

You can also find the IP using python: 

import socket 

ip = socket.gethostbyname('www.google.com')
print ip

Here is an example of a script for connecting to Google.

Python3

import socket

import sys

try:

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    print ("Socket successfully created")

except socket.error as err:

    print ("socket creation failed with error %s" %(err))

port = 80

try:

    host_ip = socket.gethostbyname('www.google.com')

except socket.gaierror:

    print ("there was an error resolving the host")

    sys.exit()

s.connect((host_ip, port))

print ("the socket has successfully connected to google")

Output : 

Socket successfully created
the socket has successfully connected to google 
on port == 173.194.40.19
  • First of all, we made a socket.
  • Then we resolved google’s IP and lastly, we connected to google.
  • Now we need to know how can we send some data through a socket.
  • For sending data the socket library has a sendall function. This function allows you to send data to a server to which the socket is connected and the server can also send data to the client using this function.

A simple server-client program : 
 

Server : 

A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listening mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client. 

Python3

import socket            

s = socket.socket()        

print ("Socket successfully created")

port = 12345               

s.bind(('', port))        

print ("socket binded to %s" %(port))

s.listen(5)    

print ("socket is listening")           

while True:

  c, addr = s.accept()    

  print ('Got connection from', addr )

  c.send('Thank you for connecting'.encode())

  c.close()

  break

  • First of all, we import socket which is necessary.
  • Then we made a socket object and reserved a port on our pc.
  • After that, we bound our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer.
  • After that we put the server into listening mode.5 here means that 5 connections are kept waiting if the server is busy and if a 6th socket tries to connect then the connection is refused.
  • At last, we make a while loop and start to accept all incoming connections and close those connections after a thank you message to all connected sockets.

Client : 
Now we need something with which a server can interact. We could telnet to the server like this just to know that our server is working. Type these commands in the terminal: 

# start the server
$ python server.py

# keep the above terminal open 
# now open another terminal and type: 
 
$ telnet localhost 12345

If ‘telnet’ is not recognized. On windows search windows features and turn on the “telnet client” feature.

Output : 

# in the server.py terminal you will see
# this output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 52617)
# In the telnet terminal you will get this:
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Thank you for connectingConnection closed by foreign host.

This output shows that our server is working.
Now for the client-side: 

Python3

import socket            

s = socket.socket()        

port = 12345               

s.connect(('127.0.0.1', port))

print (s.recv(1024).decode())

s.close()    

  • First of all, we make a socket object.
  • Then we connect to localhost on port 12345 (the port on which our server runs) and lastly, we receive data from the server and close the connection.
  • Now save this file as client.py and run it from the terminal after starting the server script.
# start the server:
$ python server.py
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 52617)
# start the client:
$ python client.py
Thank you for connecting

Reference: Python Socket Programming
This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Reconnect a Python socket after it has lost its connection

Learn how to automatically attempt to reconnect a Python client socket once it has lost its connection to the server socket


When creating a network using sockets, sometimes it can be necessary to implement an automatic re-connection system for when a client socket loses its connection to the server socket. This could be a necessity to the application, or just for the user’s convenience.

In Python, when a socket loses its connection to the host, the socket will be closed by the operating system, this will result in errors if you try to read or write to the socket stream, this at least gives you a way to detect the loss of connection. All you will need to do afterwards is create a new socket and attempt to reconnect to the host.

The below examples are compatible with Python version 3 and up.

Detecting a loss of connection to the server

When a loss of connectivity occurs between the client and server socket, the operating system closes the socket that was holding the connection open, so if you attempt to read or write to the socket stream, it will result in an exception.

To detect a loss of connection, all you need to do is surround any socket read or write operations in a try-except statement that listens for a socket exception.

try:  
    clientSocket.send( bytes( "test", "UTF-8" ) )  
except socket.error:  
    

If this exception is caught, you will know that you most likely need to reconnect to the server.

Reconnecting to the server once loss of connection is detected

As the socket object is no longer useful after the connection is lost, it is necessary to create a new socket object (this can be assigned to the initial socket variable).

Once you have recreated the client socket, you can then try to reconnect to the server using the connect() method. The problem with this is that the issue that caused the loss of connection may still be affecting the system, this means the connect() method could result in an exception such as a «ConnectionRefusedError» (caused by the server not actively listening for connections).

A simple solution to this issue is to place the connect() method within a while loop and surround it with a try-except statement. If the connection is successful, then the application will continue with the rest of the script, otherwise it will wait a few seconds and attempt to reconnect again.

print( "connection lost... reconnecting" )  
connected = False  
  

clientSocket = socket.socket()  
  
while not connected:  
    
    try:  
        clientSocket.connect( ( host, port ) )  
        connected = True  
        print( "re-connection successful" )  
    except socket.error:  
        sleep( 2 )  
  

The above script will keep the application within the while loop until it has successfully reconnected to the server socket.

Full example

Here we will create a simple local server and client that will both send and receive simple messages from each-other for as long as they are connected. If the client loses connection to the server, it will try to reconnect.

server.py

import socket  
from time import sleep  
  

serverSocket = socket.socket()  
host = socket.gethostname()  
port = 25000 
serverSocket.bind( ( host, port ) )  
serverSocket.listen( 1 )  
  
con, addr = serverSocket.accept()  
  
print( "connected to client" )  
  
while True:  
    
    con.send( bytes( "Server wave", "UTF-8" ) )  
  
    
    message = con.recv( 1024 ).decode( "UTF-8" )  
    print( message )  
  
    
    sleep( 1 )  
  
con.close();  

client.py

import socket  
from time import sleep  
  

clientSocket = socket.socket()  
host = socket.gethostname()  
port = 25000  
clientSocket.connect( ( host, port ) )  
  

connected = True  
print( "connected to server" )  
  
while True:  
    
    try:  
        message = clientSocket.recv( 1024 ).decode( "UTF-8" )  
        clientSocket.send( bytes( "Client wave", "UTF-8" ) )  
        print( message )  
    except socket.error:  
        
        connected = False  
        clientSocket = socket.socket()  
        print( "connection lost... reconnecting" )  
        while not connected:  
            
            try:  
                clientSocket.connect( ( host, port ) )  
                connected = True  
                print( "re-connection successful" )  
            except socket.error:  
                sleep( 2 )  
  
clientSocket.close();  

If you have any questions or anything to add feel free to leave a comment below!


person Author: Instructobit
access_time Modified: 2 years ago
bar_chart Views: 50435
more Tags:

networks

python

Auto saves

Looking for connections in the world of IT? Join our community and find other helpful and friendly developers, admins, engineers, and other IT people here!

close

Recommended

See something you don’t agree with or feel could be improved?


Not finding what you were looking for or have an idea for a tutorial?

close

Socket programming in Python

This is a quick guide/tutorial on socket programming in python. Socket programming python is very similar to C.

To summarise the basics, sockets are the fundamental «things» behind any kind of network communications done by your computer.

For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype.

Any network communication goes through a socket.

In this tutorial we shall be programming Tcp sockets in python. You can also program udp sockets in python.

Coding a simple socket client

First we shall learn how to code a simple socket client in python. A client connects to a remote host using sockets and sends and receives some data.

1. Creating a socket

This first thing to do is create a socket. The socket.socket function does this.
Quick Example :

#Socket client example in python

import socket	#for sockets

#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print 'Socket Created'

Function socket.socket creates a socket and returns a socket descriptor which can be used in other socket related functions

The above code will create a socket with the following properties …

Address Family : AF_INET (this is IP version 4 or IPv4)
Type : SOCK_STREAM (this means connection oriented TCP protocol)

Error handling

If any of the socket functions fail then python throws an exception called socket.error which must be caught.

#handling errors in python socket programs

import socket	#for sockets
import sys	#for exit

try:
	#create an AF_INET, STREAM socket (TCP)
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
	print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
	sys.exit();

print 'Socket Created'

Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server using this socket. We can connect to www.google.com

Note

Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.

2. Connect to a Server

We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to. So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample.

First get the IP address of the remote host/url

Before connecting to a remote host, its ip address is needed. In python the getting the ip address is quite simple.

import socket	#for sockets
import sys	#for exit

try:
	#create an AF_INET, STREAM socket (TCP)
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
	print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
	sys.exit();

print 'Socket Created'

host = 'www.google.com'

try:
	remote_ip = socket.gethostbyname( host )

except socket.gaierror:
	#could not resolve
	print 'Hostname could not be resolved. Exiting'
	sys.exit()
	
print 'Ip address of ' + host + ' is ' + remote_ip

Now that we have the ip address of the remote host/system, we can connect to ip on a certain ‘port’ using the connect function.

Quick example

import socket	#for sockets
import sys	#for exit

try:
	#create an AF_INET, STREAM socket (TCP)
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
	print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
	sys.exit();

print 'Socket Created'

host = 'www.google.com'
port = 80

try:
	remote_ip = socket.gethostbyname( host )

except socket.gaierror:
	#could not resolve
	print 'Hostname could not be resolved. Exiting'
	sys.exit()
	
print 'Ip address of ' + host + ' is ' + remote_ip

#Connect to remote server
s.connect((remote_ip , port))

print 'Socket Connected to ' + host + ' on ip ' + remote_ip

Run the program

$ python client.py
Socket Created
Ip address of www.google.com is 74.125.236.83
Socket Connected to www.google.com on ip 74.125.236.83

It creates a socket and then connects. Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection. This logic can be used to build a port scanner.

OK, so we are now connected. Lets do the next thing , sending some data to the remote server.

Free Tip

The concept of «connections» apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable «stream» of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by data from other pipes. Another important property of stream connections is that packets have an «order» or «sequence».

Other sockets like UDP , ICMP , ARP dont have a concept of «connection». These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.

3. Sending Data

Function sendall will simply send data.
Lets send some data to google.com

import socket	#for sockets
import sys	#for exit

try:
	#create an AF_INET, STREAM socket (TCP)
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
	print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
	sys.exit();

print 'Socket Created'

host = 'www.google.com'
port = 80

try:
	remote_ip = socket.gethostbyname( host )

except socket.gaierror:
	#could not resolve
	print 'Hostname could not be resolved. Exiting'
	sys.exit()
	
print 'Ip address of ' + host + ' is ' + remote_ip

#Connect to remote server
s.connect((remote_ip , port))

print 'Socket Connected to ' + host + ' on ip ' + remote_ip

#Send some data to remote server
message = "GET / HTTP/1.1rnrn"

try :
	#Set the whole string
	s.sendall(message)
except socket.error:
	#Send failed
	print 'Send failed'
	sys.exit()

print 'Message send successfully'

In the above example , we first connect to an ip address and then send the string message «GET / HTTP/1.1rnrn» to it. The message is actually an «http command» to fetch the mainpage of a website.

Now that we have send some data , its time to receive a reply from the server. So lets do it.

4. Receiving Data

Function recv is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.

#Socket client example in python

import socket	#for sockets
import sys	#for exit

#create an INET, STREAMing socket
try:
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
	print 'Failed to create socket'
	sys.exit()
	
print 'Socket Created'

host = 'www.google.com';
port = 80;

try:
	remote_ip = socket.gethostbyname( host )

except socket.gaierror:
	#could not resolve
	print 'Hostname could not be resolved. Exiting'
	sys.exit()

#Connect to remote server
s.connect((remote_ip , port))

print 'Socket Connected to ' + host + ' on ip ' + remote_ip

#Send some data to remote server
message = "GET / HTTP/1.1rnrn"

try :
	#Set the whole string
	s.sendall(message)
except socket.error:
	#Send failed
	print 'Send failed'
	sys.exit()

print 'Message send successfully'

#Now receive data
reply = s.recv(4096)

print reply

Here is the output of the above code :

$ python client.py
Socket Created
Ip address of www.google.com is 74.125.236.81
Socket Connected to www.google.com on ip 74.125.236.81
Message send successfully
HTTP/1.1 302 Found
Location: http://www.google.co.in/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com
Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com
Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com
Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com
Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com
Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com
Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com
Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com
Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com
Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com
Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com
Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com
Set-Cookie: PREF=ID=51f26964398d27b0:FF=0:TM=1343026094:LM=1343026094:S=pa0PqX9FCPvyhBHJ; expires=Wed, 23-Jul-2014 06:48:14 GMT; path=/; domain=.google.com

Google.com replied with the content of the page we requested. Quite simple!
Now that we have received our reply, its time to close the socket.

5. Close socket

Function close is used to close the socket.

s.close()

Thats it.

Lets Revise

So in the above example we learned how to :
1. Create a socket
2. Connect to remote server
3. Send some data
4. Receive a reply

Its useful to know that your web browser also does the same thing when you open www.google.com
This kind of socket activity represents a CLIENT. A client is a system that connects to a remote system to fetch data.

The other kind of socket activity is called a SERVER. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.

Now its time to do some server tasks using sockets.

Coding socket servers in Python

OK now onto server things. Servers basically do the following :

1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send

We have already learnt how to open a socket. So the next thing would be to bind it.

1. Bind a socket

Function bind can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.

Quick example

import socket
import sys

HOST = ''	# Symbolic name meaning all available interfaces
PORT = 8888	# Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
	s.bind((HOST, PORT))
except socket.error , msg:
	print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
	sys.exit()
	
print 'Socket bind complete'

Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.

This makes it obvious that you cannot have 2 sockets bound to the same port. There are exceptions to this rule but we shall look into that in some other article.

2. Listen for incoming connections

After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function socket_listen is used to put the socket in listening mode. Just add the following line after bind.

s.listen(10)
print 'Socket now listening'

The parameter of the function listen is called backlog. It controls the number of incoming connections that are kept «waiting» if the program is already busy. So by specifying 10, it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected. This will be more clear after checking socket_accept.

Now comes the main part of accepting new connections.

3. Accept connection

Function socket_accept is used for this.

import socket
import sys

HOST = ''	# Symbolic name meaning all available interfaces
PORT = 8888	# Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
	s.bind((HOST, PORT))
except socket.error , msg:
	print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
	sys.exit()
	
print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#wait to accept a connection - blocking call
conn, addr = s.accept()

#display client information
print 'Connected with ' + addr[0] + ':' + str(addr[1])

Output

Run the program. It should show

$ python server.py
Socket created
Socket bind complete
Socket now listening

So now this program is waiting for incoming connections on port 8888. Dont close this program , keep it running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type

$ telnet localhost 8888

It will immediately show

$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.

And the server output will show

$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:59954

So we can see that the client connected to the server. Try the above steps till you get it working perfect.

We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.

Function sendall can be used to send something to the socket of the incoming connection and the client should see it. Here is an example :

import socket
import sys

HOST = ''	# Symbolic name meaning all available interfaces
PORT = 8888	# Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
	s.bind((HOST, PORT))
except socket.error , msg:
	print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
	sys.exit()
	
print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#wait to accept a connection - blocking call
conn, addr = s.accept()

print 'Connected with ' + addr[0] + ':' + str(addr[1])

#now keep talking with the client
data = conn.recv(1024)
conn.sendall(data)

conn.close()
s.close()

Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :

$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
happy
Connection closed by foreign host.

So the client(telnet) received a reply from server.

We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.

It means that a server is supposed to be running all the time. After all its a server meant to serve.

So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept in a loop so that it can receive incoming connections all the time.

4. Live Server — accepting multiple connections

So a live server will be alive always. Lets code this up

import socket
import sys

HOST = ''	# Symbolic name meaning all available interfaces
PORT = 5000	# Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
	s.bind((HOST, PORT))
except socket.error , msg:
	print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
	sys.exit()
	
print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
	conn, addr = s.accept()
	print 'Connected with ' + addr[0] + ':' + str(addr[1])
	
	data = conn.recv(1024)
	reply = 'OK...' + data
	if not data: 
		break
	
	conn.sendall(reply)

conn.close()
s.close()

We havent done a lot there. Just put the socket_accept in a loop.

Now run the server program in 1 terminal , and open 3 other terminals.
From each of the 3 terminal do a telnet to the server port.

Each of the telnet terminal would show :

$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
OK .. happy
Connection closed by foreign host.

And the server terminal would show

$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:60225
Connected with 127.0.0.1:60237
Connected with 127.0.0.1:60239

So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program. All telnet terminals would show «Connection closed by foreign host.»

Good so far. But still the above code does not establish an effective communication channel between the server and the client.

The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time.

So now its time to handle the connections, and handle multiple connections together.

5. Handling Multiple Connections

To handle every connection we need a separate handling code to run along with the main server accepting connections. One way to achieve this is using threads.

The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.

We shall now use threads to create handlers for each connection the server accepts.

import socket
import sys
from thread import *

HOST = ''	# Symbolic name meaning all available interfaces
PORT = 8888	# Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
	s.bind((HOST, PORT))
except socket.error , msg:
	print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
	sys.exit()
	
print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn):
	#Sending message to connected client
	conn.send('Welcome to the server. Type something and hit entern') #send only takes string
	
	#infinite loop so that function do not terminate and thread do not end.
	while True:
		
		#Receiving from client
		data = conn.recv(1024)
		reply = 'OK...' + data
		if not data: 
			break
	
		conn.sendall(reply)
	
	#came out of loop
	conn.close()

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
	conn, addr = s.accept()
	print 'Connected with ' + addr[0] + ':' + str(addr[1])
	
	#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
	start_new_thread(clientthread ,(conn,))

s.close()

Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.

The telnet terminals would show :

$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Welcome to the server. Type something and hit enter
hi
OK...hi
asd
OK...asd
cv
OK...cv

The server terminal might look like this

$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:60730
Connected with 127.0.0.1:60731

The above connection handler takes some input from the client and replies back with the same.

So now we have a server thats communicative. Thats useful now.

Conclusion

By now you must have learned the basics of socket programming in python. You can try out some experiments like writing a chat client or something similar.

When testing the code you might face this error

Bind failed. Error Code : 98 Message Address already in use

When it comes up, simply change the port number and the server would run fine.

If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.

The following are 30
code examples of socket.error().
You can vote up the ones you like or vote down the ones you don’t like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
socket
, or try the search function

.

Example #1

def __init__(self, eventHandler):
        threading.Thread.__init__(self)
        self.name = 'Server'
        self.daemon = True
        self._eventHandler = eventHandler

        self._client = None
        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        try:
            self._server.bind(('', PORT))
            self._server.listen(5)
        except socket.error:
            event = Event(Events.SCAN_ERROR, msg='Could not start server')
            post_event(eventHandler, event)
            return

        self._cancel = False
        self.start() 

Example #2

def send_mail(self, msg):
        if _mail.recip:
            # write message to temp file for rate limit
            with open(self.temp_msg, 'w+') as f:
                f.write(msg)

            self.current_time()

            message = MIMEMultipart()
            message['From'] = _mail.s_addr
            message['To'] = _mail.recip
            message['Subject'] = _mail.subject
            message['Date'] = formatdate(localtime=True)
            message.attach(MIMEText('{} {}'.format(self.time, msg), 'plain'))
            text = message.as_string()

            try:
                server = smtplib.SMTP(_mail.server, _mail.port)
            except socket.error as err:
                playout_logger.error(err)
                server = None

            if server is not None:
                server.starttls()
                try:
                    login = server.login(_mail.s_addr, _mail.s_pass)
                except smtplib.SMTPAuthenticationError as serr:
                    playout_logger.error(serr)
                    login = None

                if login is not None:
                    server.sendmail(_mail.s_addr, _mail.recip, text)
                    server.quit() 

Example #3

def test_Content_Length_in(self):
        # Try a non-chunked request where Content-Length exceeds
        # server.max_request_body_size. Assert error before body send.
        self.persistent = True
        conn = self.HTTP_CONN
        conn.putrequest('POST', '/upload', skip_host=True)
        conn.putheader('Host', self.HOST)
        conn.putheader('Content-Type', 'text/plain')
        conn.putheader('Content-Length', '9999')
        conn.endheaders()
        response = conn.getresponse()
        self.status, self.headers, self.body = webtest.shb(response)
        self.assertStatus(413)
        self.assertBody('The entity sent with the request exceeds '
                        'the maximum allowed bytes.')
        conn.close() 

Example #4

def test_garbage_in(self):
        # Connect without SSL regardless of server.scheme
        c = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
        c._output(b'gjkgjklsgjklsgjkljklsg')
        c._send_output()
        response = c.response_class(c.sock, method='GET')
        try:
            response.begin()
            self.assertEqual(response.status, 400)
            self.assertEqual(response.fp.read(22),
                             b'Malformed Request-Line')
            c.close()
        except socket.error:
            e = sys.exc_info()[1]
            # "Connection reset by peer" is also acceptable.
            if e.errno != errno.ECONNRESET:
                raise 

Example #5

def __init__(self, address, port, key, logger, sname):
        self.address = address
        self.port = int(port)
        self.key = key
        self.logger = logger
        self.serverName = sname

        while True: # keep going until we break out inside the loop
            try:
                self.logger.debug('Attempting to connect to '+self.serverName+' server at '+str(self.address)+' port '+str(self.port))
                self.conn = Client((self.address, self.port))
                self.logger.debug('Connect to '+self.serverName+' successful.')
                break
            except SocketError as serr:
                if serr.errno == errno.ECONNREFUSED:
                    self.logger.debug('Connect to '+self.serverName+' failed because connection was refused (the server is down). Trying again.')
                else:
                    # Not a recognized error. Treat as fatal.
                    self.logger.debug('Connect to '+self.serverName+' gave socket error '+str(serr.errno))
                    raise serr
            except:
                self.logger.exception('Connect to '+self.serverName+' threw unknown exception')
                raise 

Example #6

def send(self, msg):
        # TODO: Busy wait will do for initial startup but for dealing with server down in the middle of things
        # TODO: then busy wait is probably inappropriate.
        while True: # keep going until we break out inside the loop
            try:
                self.logger.debug('Attempting to connect to '+self.serverName+' server at '+str(self.address)+' port '+str(self.port))
                conn = Client((self.address, self.port))
                self.logger.debug('Connect to '+self.serverName+' successful.')
                break
            except SocketError as serr:
                if serr.errno == errno.ECONNREFUSED:
                    self.logger.debug('Connect to '+self.serverName+' failed because connection was refused (the server is down). Trying again.')
                else:
                    # Not a recognized error. Treat as fatal.
                    self.logger.debug('Connect to '+self.serverName+' gave socket error '+str(serr.errno))
                    raise serr
            except:
                self.logger.exception('Connect to '+self.serverName+' threw unknown exception')
                raise

        conn.send(msg)

        conn.close() 

Example #7

def send(self, msg):
        # TODO: Busy wait will do for initial startup but for dealing with server down in the middle of things
        # TODO: then busy wait is probably inappropriate.
        while True: # keep going until we break out inside the loop
            try:
                self.logger.debug('Attempting to connect to '+self.serverName+' server at '+str(self.address)+' port '+str(self.port))
                conn = hub.connect((self.address, self.port))
                self.logger.debug('Connect to '+self.serverName+' successful.')
                break
            except SocketError as serr:
                if serr.errno == errno.ECONNREFUSED:
                    self.logger.debug('Connect to '+self.serverName+' failed because connection was refused (the server is down). Trying again.')
                else:
                    # Not a recognized error. Treat as fatal.
                    self.logger.debug('Connect to '+self.serverName+' gave socket error '+str(serr.errno))
                    raise serr
            except:
                self.logger.exception('Connect to '+self.serverName+' threw unknown exception')
                raise

        conn.sendall(msg)

        conn.close() 

Example #8

def create_command_listener (baddr, port):
    try:
        if port is None:
            try:
                if os.path.exists(baddr):
                    os.unlink(baddr)
            except OSError:
                print 'could not remove old unix socket ' + baddr
                return
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
            s.bind(baddr)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((baddr, int(port)))
    except socket.error , msg:
        print 'Bind failed on command interface ' + baddr + ' port ' + str(port) + ' Error Code : ' + str(msg[0]) + ' Message ' + msg[1] + 'n'
        return 

Example #9

def validate_optional_args(args):
	"""Check if an argument was provided that depends on a module that may
	not be part of the Python standard library.

	If such an argument is supplied, and the module does not exist, exit
	with an error stating which module is missing.
	"""
	optional_args = {
		'json': ('json/simplejson python module', json),
		'secure': ('SSL support', HTTPSConnection),
	}

	for arg, info in optional_args.items():
		if getattr(args, arg, False) and info[1] is None:
			raise SystemExit('%s is not installed. --%s is '
							 'unavailable' % (info[0], arg)) 

Example #10

def send(self, channel_type, message, additional_data):
		if channel_type == common.CONTROL_CHANNEL_BYTE:
			transformed_message = self.transform(self.encryption, common.CONTROL_CHANNEL_BYTE+message, 1)
		else:
			transformed_message = self.transform(self.encryption, common.DATA_CHANNEL_BYTE+message, 1)

		common.internal_print("{0} sent: {1}".format(self.module_short, len(transformed_message)), 0, self.verbosity, common.DEBUG)

		# WORKAROUND?!
		# Windows: It looks like when the buffer fills up the OS does not do
		# congestion control, instead throws and exception/returns with
		# WSAEWOULDBLOCK which means that we need to try it again later.
		# So we sleep 100ms and hope that the buffer has more space for us.
		# If it does then it sends the data, otherwise tries it in an infinite
		# loop...
		while True:
			try:
				return self.comms_socket.send(struct.pack(">H", len(transformed_message))+transformed_message)
			except socket.error as se:
				if se.args[0] == 10035: # WSAEWOULDBLOCK
					time.sleep(0.1)
					pass
				else:
					raise 

Example #11

def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 

Example #12

def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = SCTP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 

Example #13

def communication_initialization(self):
		try:
		
			common.internal_print("Waiting for upgrade request", 0, self.verbosity, common.DEBUG)
			response = self.comms_socket.recv(4096)

			if len(response) == 0:
				common.internal_print("Connection was dropped", 0, self.verbosity, common.DEBUG)
				self.cleanup()
				sys.exit(-1)
			handshake_key = self.WebSocket_proto.get_handshake_init(response)
			if handshake_key == None:
				common.internal_print("No WebSocket-Key in request", -1, self.verbosity, common.DEBUG)
				self.cleanup()
				sys.exit(-1)

			handshake = self.WebSocket_proto.calculate_handshake(handshake_key)
			response = self.WebSocket_proto.switching_protocol(handshake)
			self.comms_socket.send(response)
		except:
			common.internal_print("Socket error", -1, self.verbosity, common.DEBUG)
			self.cleanup()
			sys.exit(-1)

		return 

Example #14

def connect(self):
		try:
			common.internal_print("Starting client: {0}".format(self.get_module_name()))
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_hello()
			self.communication(False)

		except KeyboardInterrupt:
			self.do_logoff()
			self.cleanup()
			raise
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 

Example #15

def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_check()
			self.communication(True)

		except KeyboardInterrupt:
			self.cleanup()
			raise
		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 

Example #16

def ReleasePowerAssertion(io_lib, assertion_id):
  """Releases a power assertion.

  Assertions are released with IOPMAssertionRelease, however if they are not,
  assertions are automatically released when the process exits, dies or
  crashes, i.e. a crashed process will not prevent idle sleep indefinitely.

  Args:
    io_lib: IOKit library from ConfigureIOKit()
    assertion_id: c_uint, assertion identification number from
        CreatePowerAssertion()

  Returns:
    0 if successful, stderr otherwise.
  """
  try:
    return io_lib.IOPMAssertionRelease(assertion_id)
  except AttributeError:
    return 'IOKit library returned an error.' 

Example #17

def run(self):
        try:
            self.sse = ClosableSSEClient(self.url)
            for msg in self.sse:
                event = msg.event
                if event is not None and event in ('put', 'patch'):
                    response = json.loads(msg.data)
                    if response is not None:
                        # Default to CHILD_CHANGED event
                        occurred_event = FirebaseEvents.CHILD_CHANGED
                        if response['data'] is None:
                            occurred_event = FirebaseEvents.CHILD_DELETED

                        # Get the event I'm trying to listen to
                        ev = FirebaseEvents.id(self.event_name)
                        if occurred_event == ev or ev == FirebaseEvents.CHILD_CHANGED:
                            self.callback(event, response)
        except socket.error:
            pass 

Example #18

def send_command(connection, message):
    try:
        connection.sendall(message)

        response = connection.recv(4096)
        global current_client_id

        if not response:  # Empty
            current_client_id = None
            connections.remove(connection)

            status_messages.append(MESSAGE_ATTENTION + "Client disconnected!")
            return None
        else:
            return response
    except socket.error:
        current_client_id = None
        connections.remove(connection)

        status_messages.append(MESSAGE_ATTENTION + "Client disconnected!")
        return None 

Example #19

def CheckUrl(self, url, status_codes, max_retries=5):
    """Check a remote URL for availability.

    Args:
      url: A URL to access.
      status_codes: Acceptable status codes for the connection (list).
      max_retries: Number of retries before giving up.

    Returns:
      True if accessing the file produced one of status_codes.
    """
    try:
      self._OpenStream(url, max_retries=max_retries, status_codes=status_codes)
      return True
    except DownloadError as e:
      logging.error(e)
    return False 

Example #20

def _StoreDebugInfo(self, file_stream, socket_error=None):
    """Gathers debug information for use when file downloads fail.

    Args:
      file_stream:  The file stream object of the file being downloaded.
      socket_error: Store the error raised from the socket class with
        other debug info.

    Returns:
      debug_info:  A dictionary containing various pieces of debugging
          information.
    """
    if socket_error:
      self._debug_info['socket_error'] = socket_error
    if file_stream:
      for header in file_stream.info().header_items():
        self._debug_info[header[0]] = header[1]
    self._debug_info['current_time'] = time.strftime(
        '%A, %d %B %Y %H:%M:%S UTC') 

Example #21

def deliver_dnotify(self, dnstring, _recurse = 0):
        if self.s == None:
            self.connect()
        if _recurse > _MAX_RECURSE:
            raise Exception('Cannot reconnect: %s', self.spath)
        if not dnstring.endswith('n'):
            dnstring += 'n'
        while True:
            try:
                self.s.send(dnstring)
                break
            except socket.error as why:
                if why[0] == EINTR:
                    continue
                elif why[0] in (EPIPE, ENOTCONN, ECONNRESET):
                    self.s = None
                    return self.deliver_dnotify(dnstring, _recurse + 1)
                raise why
        # Clean any incoming data on the socket
        if len(self.poller.poll(0)) > 0:
            try:
                self.s.recv(1024)
            except:
                pass
        return 

Example #22

def run(self):
        #print(self.run, 'enter')
        while True:
            #print(self.run, 'cycle')
            pollret = dict(self.pollobj.poll()).get(self.fileno, 0)
            if pollret & POLLNVAL != 0:
                break
            if pollret & POLLIN == 0:
                continue
            try:
                clientsock, addr = self.clicm.serversock.accept()
            except Exception as why:
                if isinstance(why, socket.error):
                    if why.errno == ECONNABORTED:
                        continue
                    elif why.errno == EBADF:
                        break
                    else:
                        raise
                dump_exception('CLIConnectionManager: unhandled exception when accepting incoming connection')
                break
            #print(self.run, 'handle_accept')
            ED2.callFromThread(self.clicm.handle_accept, clientsock, addr)
        self.clicm = None
        #print(self.run, 'exit') 

Example #23

def validate_ffmpeg_libs():
    if 'libx264' not in FF_LIBS['libs']:
        playout_logger.error('ffmpeg contains no libx264!')
    if 'libfdk-aac' not in FF_LIBS['libs']:
        playout_logger.warning(
            'ffmpeg contains no libfdk-aac! No high quality aac...')
    if 'libtwolame' not in FF_LIBS['libs']:
        playout_logger.warning(
            'ffmpeg contains no libtwolame!'
            ' Loudness correction use mp2 audio codec...')
    if 'tpad' not in FF_LIBS['filters']:
        playout_logger.error('ffmpeg contains no tpad filter!')
    if 'zmq' not in FF_LIBS['filters']:
        playout_logger.error(
            'ffmpeg contains no zmq filter!  Text messages will not work...')


# ------------------------------------------------------------------------------
# probe media infos
# ------------------------------------------------------------------------------ 

Example #24

def ffmpeg_stderr_reader(std_errors, decoder):
    if decoder:
        logger = decoder_logger
        prefix = DEC_PREFIX
    else:
        logger = encoder_logger
        prefix = ENC_PREFIX

    try:
        for line in std_errors:
            if _log.ff_level == 'INFO':
                logger.info('{}{}'.format(
                    prefix, line.decode("utf-8").rstrip()))
            elif _log.ff_level == 'WARNING':
                logger.warning('{}{}'.format(
                    prefix, line.decode("utf-8").rstrip()))
            else:
                logger.error('{}{}'.format(
                    prefix, line.decode("utf-8").rstrip()))
    except ValueError:
        pass 

Example #25

def proxy(src, dst, callback=None):
    timeout = 10
    try:
        read_ready, _, _ = select.select([src], [], [], timeout)
        while len(read_ready):
            if callback:
                callback(src, dst)
            else:
                dst.send(src.recv(8192))
            read_ready, _, _ = select.select([src], [], [], timeout)
    except (socket.error, select.error, OSError, ValueError):
        pass
    try:
        src.shutdown(socket.SHUT_RDWR)
    except (socket.error, OSError, ValueError):
        pass
    src.close()
    try:
        dst.shutdown(socket.SHUT_RDWR)
    except (socket.error, OSError, ValueError):
        pass
    dst.close() 

Example #26

def _raw_read(self):
        """
        Reads data from the socket and writes it to the memory bio
        used by libssl to decrypt the data. Returns the unencrypted
        data for the purpose of debugging handshakes.

        :return:
            A byte string of ciphertext from the socket. Used for
            debugging the handshake only.
        """

        data = self._raw_bytes
        try:
            data += self._socket.recv(8192)
        except (socket_.error):
            pass
        output = data
        written = libssl.BIO_write(self._rbio, data, len(data))
        self._raw_bytes = data[written:]
        return output 

Example #27

def _read_remaining(socket):
    """
    Reads everything available from the socket - used for debugging when there
    is a protocol error

    :param socket:
        The socket to read from

    :return:
        A byte string of the remaining data
    """

    output = b''
    old_timeout = socket.gettimeout()
    try:
        socket.settimeout(0.0)
        output += socket.recv(8192)
    except (socket_.error):
        pass
    finally:
        socket.settimeout(old_timeout)
    return output 

Example #28

def run(self):
        while not self._cancel:
            if self._client is None:
                endpoints = [self._server]
            else:
                endpoints = [self._server, self._client]

            read, _write, error = select.select(endpoints, [], [], 0.5)

            for sock in read:
                if sock is self._server:
                    try:
                        client, _addr = self._server.accept()
                        if self._client is not None:
                            self._client.close()
                        self._client = client
                    except socket.error:
                        self._client = None

            for sock in error:
                if sock is self._client:
                    self._client = None
                sock.close() 

Example #29

def send(self, data):
        if self._client is not None:
            try:
                self._client.sendall(data)
                self._client.sendall('rn')
            except socket.error:
                self._client.close()
                self._client = None 

Example #30

def dict_to_xml(d, sign=None):
    xml = ["<xml>n"]
    for k in sorted(d):
        # use sorted to avoid test error on Py3k
        v = d[k]
        if isinstance(v, int) or (isinstance(v, str) and v.isdigit()):
            xml.append(f"<{to_text(k)}>{to_text(v)}</{to_text(k)}>n")
        else:
            xml.append(f"<{to_text(k)}><![CDATA[{to_text(v)}]]></{to_text(k)}>n")
    if sign:
        xml.append(f"<sign><![CDATA[{to_text(sign)}]]></sign>n</xml>")
    else:
        xml.append("</xml>")
    return "".join(xml) 

Понравилась статья? Поделить с друзьями:
  • Python error unindent does not match any outer indentation level
  • Python error running main
  • Python error loading mysqldb module
  • Python error list index out of range
  • Python error get traceback