This module provides access to the BSDsocket interface. It is available onall modern Unix systems, Windows, MacOS, OS/2, and probably additionalplatforms.
Note
Some behavior may be platform dependent, since calls are made to the operatingsystem socket APIs.
The Python interface is a straightforward transliteration of the Unix systemcall and library interface for sockets to Python’s object-oriented style: thesocket() function returns asocket object whose methods implementthe various socket system calls. Parameter types are somewhat higher-level thanin the C interface: as withread() andwrite() operations on Pythonfiles, buffer allocation on receive operations is automatic, and buffer lengthis implicit on send operations.
See also
Depending on the system and the build options, various socket familiesare supported by this module.
The address format required by a particular socket object is automaticallyselected based on the address family specified when the socket object wascreated. Socket addresses are represented as follows:
The address of anAF_UNIX socket bound to a file system nodeis represented as a string, using the file system encoding and the'surrogateescape' error handler (seePEP 383). An address inLinux’s abstract namespace is returned as abytes object withan initial null byte; note that sockets in this namespace cancommunicate with normal file system sockets, so programs intended torun on Linux may need to deal with both types of address. A string orbytes object can be used for either type of address whenpassing it as an argument.
Changed in version 3.3:Previously,AF_UNIX socket paths were assumed to use UTF-8encoding.
A pair(host,port) is used for theAF_INET address family,wherehost is a string representing either a hostname in Internet domainnotation like'daring.cwi.nl' or an IPv4 address like'100.50.200.5',andport is an integer.
ForAF_INET6 address family, a four-tuple(host,port,flowinfo,scopeid) is used, whereflowinfo andscopeid represent thesin6_flowinfoandsin6_scope_id members instructsockaddr_in6 in C. Forsocket module methods,flowinfo andscopeid can be omitted just forbackward compatibility. Note, however, omission ofscopeid can cause problemsin manipulating scoped IPv6 addresses.
AF_NETLINK sockets are represented as pairs(pid,groups).
Linux-only support for TIPC is available using theAF_TIPCaddress family. TIPC is an open, non-IP based networked protocol designedfor use in clustered computer environments. Addresses are represented by atuple, and the fields depend on the address type. The general tuple form is(addr_type,v1,v2,v3[,scope]), where:
addr_type is one ofTIPC_ADDR_NAMESEQ,TIPC_ADDR_NAME,orTIPC_ADDR_ID.
scope is one ofTIPC_ZONE_SCOPE,TIPC_CLUSTER_SCOPE, andTIPC_NODE_SCOPE.
Ifaddr_type isTIPC_ADDR_NAME, thenv1 is the server type,v2 isthe port identifier, andv3 should be 0.
Ifaddr_type isTIPC_ADDR_NAMESEQ, thenv1 is the server type,v2is the lower port number, andv3 is the upper port number.
Ifaddr_type isTIPC_ADDR_ID, thenv1 is the node,v2 is thereference, andv3 should be set to 0.
Ifaddr_type isTIPC_ADDR_ID, thenv1 is the node,v2 is thereference, andv3 should be set to 0.
A tuple(interface,) is used for theAF_CAN address family,whereinterface is a string representing a network interface name like'can0'. The network interface name'' can be used to receive packetsfrom all network interfaces of this family.
A string or a tuple(id,unit) is used for theSYSPROTO_CONTROLprotocol of thePF_SYSTEM family. The string is the name of akernel control using a dynamically-assigned ID. The tuple can be used if IDand unit number of the kernel control are known or if a registered ID isused.
New in version 3.3.
Certain other address families (AF_BLUETOOTH,AF_PACKET)support specific representations.
For IPv4 addresses, two special forms are accepted instead of a host address:the empty string representsINADDR_ANY, and the string'<broadcast>' representsINADDR_BROADCAST. This behavior is notcompatible with IPv6, therefore, you may want to avoid these if you intendto support IPv6 with your Python programs.
If you use a hostname in thehost portion of IPv4/v6 socket address, theprogram may show a nondeterministic behavior, as Python uses the first addressreturned from the DNS resolution. The socket address will be resolveddifferently into an actual IPv4/v6 address, depending on the results from DNSresolution and/or the host configuration. For deterministic behavior use anumeric address inhost portion.
All errors raise exceptions. The normal exceptions for invalid argument typesand out-of-memory conditions can be raised; starting from Python 3.3, errorsrelated to socket or address semantics raiseOSError or one of itssubclasses (they used to raisesocket.error).
Non-blocking mode is supported throughsetblocking(). Ageneralization of this based on timeouts is supported throughsettimeout().
The modulesocket exports the following elements.
A subclass ofOSError, this exception is raised foraddress-related errors, i.e. for functions that useh_errno in the POSIXC API, includinggethostbyname_ex() andgethostbyaddr().The accompanying value is a pair(h_errno,string) representing anerror returned by a library call.h_errno is a numeric value, whilestring represents the description ofh_errno, as returned by thehstrerror() C function.
Changed in version 3.3:This class was made a subclass ofOSError.
A subclass ofOSError, this exception is raised foraddress-related errors bygetaddrinfo() andgetnameinfo().The accompanying value is a pair(error,string) representing an errorreturned by a library call.string represents the description oferror, as returned by thegai_strerror() C function. Thenumericerror value will match one of theEAI_* constantsdefined in this module.
Changed in version 3.3:This class was made a subclass ofOSError.
A subclass ofOSError, this exception is raised when a timeoutoccurs on a socket which has had timeouts enabled via a prior call tosettimeout() (or implicitly throughsetdefaulttimeout()). The accompanying value is a stringwhose value is currently always “timed out”.
Changed in version 3.3:This class was made a subclass ofOSError.
These constants represent the address (and protocol) families, used for thefirst argument tosocket(). If theAF_UNIX constant is notdefined then this protocol is unsupported. More constants may be availabledepending on the system.
These constants represent the socket types, used for the second argument tosocket(). More constants may be available depending on the system.(OnlySOCK_STREAM andSOCK_DGRAM appear to be generallyuseful.)
These two constants, if defined, can be combined with the socket types andallow you to set some flags atomically (thus avoiding possible raceconditions and the need for separate calls).
See also
Secure File Descriptor Handlingfor a more thorough explanation.
Availability: Linux >= 2.6.27.
New in version 3.2.
Many constants of these forms, documented in the Unix documentation on socketsand/or the IP protocol, are also defined in the socket module. They aregenerally used in arguments to thesetsockopt() andgetsockopt()methods of socket objects. In most cases, only those symbols that are definedin the Unix header files are defined; for a few symbols, default values areprovided.
Many constants of these forms, documented in the Linux documentation, arealso defined in the socket module.
Availability: Linux >= 2.6.25.
New in version 3.3.
Many constants of these forms, documented in the Linux documentation, arealso defined in the socket module.
Availability: Linux >= 2.6.30.
New in version 3.3.
Constants for Windows’ WSAIoctl(). The constants are used as arguments to theioctl() method of socket objects.
TIPC related constants, matching the ones exported by the C socket API. Seethe TIPC documentation for more information.
This constant contains a boolean value which indicates if IPv6 is supported onthis platform.
The following functions all createsocket objects.
Create a new socket using the given address family, socket type and protocolnumber. The address family should beAF_INET (the default),AF_INET6,AF_UNIX,AF_CAN orAF_RDS. Thesocket type should beSOCK_STREAM (the default),SOCK_DGRAM,SOCK_RAW or perhaps one of the otherSOCK_constants. The protocol number is usually zero and may be omitted in thatcase orCAN_RAW in case the address family isAF_CAN.
Changed in version 3.3:The AF_CAN family was added.The AF_RDS family was added.
Build a pair of connected socket objects using the given address family, sockettype, and protocol number. Address family, socket type, and protocol number areas for thesocket() function above. The default family isAF_UNIXif defined on the platform; otherwise, the default isAF_INET.Availability: Unix.
Changed in version 3.2:The returned socket objects now support the whole socket API, ratherthan a subset.
Connect to a TCP service listening on the Internetaddress (a 2-tuple(host,port)), and return the socket object. This is a higher-levelfunction thansocket.connect(): ifhost is a non-numeric hostname,it will try to resolve it for bothAF_INET andAF_INET6,and then try to connect to all possible addresses in turn until aconnection succeeds. This makes it easy to write clients that arecompatible to both IPv4 and IPv6.
Passing the optionaltimeout parameter will set the timeout on thesocket instance before attempting to connect. If notimeout issupplied, the global default timeout setting returned bygetdefaulttimeout() is used.
If supplied,source_address must be a 2-tuple(host,port) for thesocket to bind to as its source address before connecting. If host or portare ‘’ or 0 respectively the OS default behavior will be used.
Changed in version 3.2:source_address was added.
Changed in version 3.2:support for thewith statement was added.
Duplicate the file descriptorfd (an integer as returned by a file object’sfileno() method) and build a socket object from the result. Addressfamily, socket type and protocol number are as for thesocket() functionabove. 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 ona socket passed to a program as standard input or output (such as a serverstarted by the Unix inet daemon). The socket is assumed to be in blocking mode.
Instantiate a socket from data obtained from thesocket.share()method. The socket is assumed to be in blocking mode.
Availability: Windows.
New in version 3.3.
This is a Python type object that represents the socket object type. It is thesame astype(socket(...)).
Thesocket module also offers various network-related services:
Translate thehost/port argument into a sequence of 5-tuples that containall the necessary arguments for creating a socket connected to that service.host is a domain name, a string representation of an IPv4/v6 addressorNone.port is a string service name such as'http', a numericport number orNone. By passingNone as the value ofhostandport, you can passNULL to the underlying C API.
Thefamily,type andproto arguments can be optionally specifiedin order to narrow the list of addresses returned. Passing zero as avalue for each of these arguments selects the full range of results.Theflags argument can be one or several of theAI_* constants,and will influence how results are computed and returned.For example,AI_NUMERICHOST will disable domain name resolutionand will raise an error ifhost 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 aremeant to be passed to thesocket() function.canonname will bea string representing the canonical name of thehost ifAI_CANONNAME is part of theflags argument; elsecanonnamewill be empty.sockaddr is a tuple describing a socket address, whoseformat depends on the returnedfamily (a(address,port) 2-tuple forAF_INET, a(address,port,flowinfo,scopeid) 4-tuple forAF_INET6), and is meant to be passed to thesocket.connect()method.
The following example fetches address information for a hypothetical TCPconnection towww.python.org on port 80 (results may differ on yoursystem if IPv6 isn’t enabled):
>>>socket.getaddrinfo("www.python.org",80,proto=socket.SOL_TCP)[(2, 1, 6, '', ('82.94.164.162', 80)), (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]
Changed in version 3.2:parameters can now be passed using keyword arguments.
Return a fully qualified domain name forname. Ifname is omitted or empty,it is interpreted as the local host. To find the fully qualified name, thehostname returned bygethostbyaddr() is checked, followed by aliases for thehost, if available. The first name which includes a period is selected. Incase no fully qualified domain name is available, the hostname as returned bygethostname() is returned.
Translate a host name to IPv4 address format. The IPv4 address is returned as astring, such as'100.50.200.5'. If the host name is an IPv4 address itselfit is returned unchanged. Seegethostbyname_ex() for a more completeinterface.gethostbyname() does not support IPv6 name resolution, andgetaddrinfo() should be used instead for IPv4/v6 dual stack support.
Translate a host name to IPv4 address format, extended interface. Return atriple(hostname,aliaslist,ipaddrlist) wherehostname is the primaryhost name responding to the givenip_address,aliaslist is a (possiblyempty) list of alternative host names for the same address, andipaddrlist isa list of IPv4 addresses for the same interface on the same host (often but notalways a single address).gethostbyname_ex() does not support IPv6 nameresolution, andgetaddrinfo() should be used instead for IPv4/v6 dualstack support.
Return a string containing the hostname of the machine where the Pythoninterpreter is currently executing.
If you want to know the current machine’s IP address, you may want to usegethostbyname(gethostname()). This operation assumes that there is avalid address-to-host mapping for the host, and the assumption does notalways hold.
Note:gethostname() doesn’t always return the fully qualified domainname; usegetfqdn() (see above).
Return a triple(hostname,aliaslist,ipaddrlist) wherehostname is theprimary host name responding to the givenip_address,aliaslist is a(possibly empty) list of alternative host names for the same address, andipaddrlist is a list of IPv4/v6 addresses for the same interface on the samehost (most likely containing only a single address). To find the fully qualifieddomain name, use the functiongetfqdn().gethostbyaddr() supportsboth IPv4 and IPv6.
Translate a socket addresssockaddr into a 2-tuple(host,port). Dependingon the settings offlags, the result can contain a fully-qualified domain nameor numeric address representation inhost. Similarly,port can contain astring port name or a numeric port number.
Translate an Internet protocol name (for example,'icmp') to a constantsuitable for passing as the (optional) third argument to thesocket()function. This is usually only needed for sockets opened in “raw” mode(SOCK_RAW); for the normal socket modes, the correct protocol is chosenautomatically if the protocol is omitted or zero.
Translate an Internet service name and protocol name to a port number for thatservice. The optional protocol name, if given, should be'tcp' or'udp', otherwise any protocol will match.
Translate an Internet port number and protocol name to a service name for thatservice. The optional protocol name, if given, should be'tcp' or'udp', otherwise any protocol will match.
Convert 32-bit positive integers from network to host byte order. On machineswhere the host byte order is the same as network byte order, this is a no-op;otherwise, it performs a 4-byte swap operation.
Convert 16-bit positive integers from network to host byte order. On machineswhere the host byte order is the same as network byte order, this is a no-op;otherwise, it performs a 2-byte swap operation.
Convert 32-bit positive integers from host to network byte order. On machineswhere the host byte order is the same as network byte order, this is a no-op;otherwise, it performs a 4-byte swap operation.
Convert 16-bit positive integers from host to network byte order. On machineswhere the host byte order is the same as network byte order, this is a no-op;otherwise, it performs a 2-byte swap operation.
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 inlength. This is useful when conversing with a program that uses the standard Clibrary and needs objects of typestructin_addr, which is the C typefor the 32-bit packed binary this function returns.
inet_aton() also accepts strings with less than three dots; see theUnix manual pageinet(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 onthe underlying C implementation ofinet_aton().
inet_aton() does not support IPv6, andinet_pton() should be usedinstead for IPv4/v6 dual stack support.
Convert a 32-bit packed IPv4 address (a bytes object four characters inlength) to its standard dotted-quad string representation (for example,‘123.45.67.89’). This is useful when conversing with a program that uses thestandard C library and needs objects of typestructin_addr, whichis the C type for the 32-bit packed binary data this function takes as anargument.
If the byte sequence passed to this function is not exactly 4 bytes inlength,OSError will be raised.inet_ntoa() does notsupport IPv6, andinet_ntop() should be used instead for IPv4/v6 dualstack support.
Convert an IP address from its family-specific string format to a packed,binary format.inet_pton() is useful when a library or network protocolcalls for an object of typestructin_addr (similar toinet_aton()) orstructin6_addr.
Supported values foraddress_family are currentlyAF_INET andAF_INET6. If the IP address stringip_string is invalid,OSError will be raised. Note that exactly what is valid depends onboth the value ofaddress_family and the underlying implementation ofinet_pton().
Availability: Unix (maybe not all platforms).
Convert a packed IP address (a bytes object of some number of characters) to itsstandard, family-specific string representation (for example,'7.10.0.5' or'5aef:2b::8').inet_ntop() is useful when a library or network protocolreturns an object of typestructin_addr (similar toinet_ntoa())orstructin6_addr.
Supported values foraddress_family are currentlyAF_INET andAF_INET6. If the stringpacked_ip is not the correct length for thespecified address family,ValueError will be raised. AOSError is raised for errors from the call toinet_ntop().
Availability: Unix (maybe not all platforms).
Return the total length, without trailing padding, of an ancillarydata item with associated data of the givenlength. This valuecan often be used as the buffer size forrecvmsg() toreceive a single item of ancillary data, butRFC 3542 requiresportable applications to useCMSG_SPACE() and thus includespace for padding, even when the item will be the last in thebuffer. RaisesOverflowError iflength is outside thepermissible range of values.
Availability: most Unix platforms, possibly others.
New in version 3.3.
Return the buffer size needed forrecvmsg() toreceive an ancillary data item with associated data of the givenlength, along with any trailing padding. The buffer space neededto receive multiple items is the sum of theCMSG_SPACE()values for their associated data lengths. RaisesOverflowError iflength is outside the permissible rangeof values.
Note that some systems might support ancillary data withoutproviding this function. Also note that setting the buffer sizeusing the results of this function may not precisely limit theamount of ancillary data that can be received, since additionaldata may be able to fit into the padding area.
Availability: most Unix platforms, possibly others.
New in version 3.3.
Return the default timeout in seconds (float) for new socket objects. A valueofNone indicates that new socket objects have no timeout. When the socketmodule is first imported, the default isNone.
Set the default timeout in seconds (float) for new socket objects. Whenthe socket module is first imported, the default isNone. Seesettimeout() for possible values and their respectivemeanings.
Set the machine’s hostname toname. This will raise aOSError if you don’t have enough rights.
Availability: Unix.
New in version 3.3.
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 objects have the following methods. Except formakefile(), these correspond to Unix system calls applicableto sockets.
Accept a connection. The socket must be bound to an address and listening forconnections. The return value is a pair(conn,address) whereconn is anew socket object usable to send and receive data on the connection, andaddress is the address bound to the socket on the other end of the connection.
Bind the socket toaddress. The socket must not already be bound. (The formatofaddress depends on the address family — see above.)
Mark the socket closed. The underlying system resource (e.g. a filedescriptor) is also closed when all file objects frommakefile()are closed. Once that happens, all future operations on the socketobject will fail. The remote end will receive no more data (afterqueued data is flushed).
Sockets are automatically closed when they are garbage-collected, butit is recommended toclose() them explicitly, or to use awith statement around them.
Note
close() releases the resource associated with a connection butdoes not necessarily close the connection immediately. If you wantto close the connection in a timely fashion, callshutdown()beforeclose().
Connect to a remote socket ataddress. (The format ofaddress depends on theaddress family — see above.)
Likeconnect(address), but return an error indicator instead of raising anexception for errors returned by the C-levelconnect() call (otherproblems, such as “host not found,” can still raise exceptions). The errorindicator is0 if the operation succeeded, otherwise the value of theerrno variable. This is useful to support, for example, asynchronousconnects.
Put the socket object into closed state without actually closing theunderlying file descriptor. The file descriptor is returned, and canbe reused for other purposes.
New in version 3.2.
Return the socket’s file descriptor (a small integer). This is useful withselect.select().
Under Windows the small integer returned by this method cannot be used where afile descriptor can be used (such asos.fdopen()). Unix does not havethis limitation.
Return the remote address to which the socket is connected. This is useful tofind out the port number of a remote IPv4/v6 socket, for instance. (The formatof the address returned depends on the address family — see above.) On somesystems this function is not supported.
Return the socket’s own address. This is useful to find out the port number ofan IPv4/v6 socket, for instance. (The format of the address returned depends onthe address family — see above.)
Return the value of the given socket option (see the Unix man pagegetsockopt(2)). The needed symbolic constants (SO_* etc.)are defined in this module. Ifbuflen is absent, an integer option is assumedand its integer value is returned by the function. Ifbuflen is present, itspecifies the maximum length of the buffer used to receive the option in, andthis buffer is returned as a bytes object. It is up to the caller to decode thecontents of the buffer (see the optional built-in modulestruct for a wayto decode C structures encoded as byte strings).
Return the timeout in seconds (float) associated with socket operations,orNone if no timeout is set. This reflects the last call tosetblocking() orsettimeout().
| Platform: | Windows |
|---|
Theioctl() method is a limited interface to the WSAIoctl systeminterface. Please refer to theWin32 documentation for moreinformation.
On other platforms, the genericfcntl.fcntl() andfcntl.ioctl()functions may be used; they accept a socket object as their first argument.
Listen for connections made to the socket. Thebacklog argument specifies themaximum number of queued connections and should be at least 0; the maximum valueis system-dependent (usually 5), the minimum value is forced to 0.
Return afile object associated with the socket. The exact returnedtype depends on the arguments given tomakefile(). These arguments areinterpreted the same way as by the built-inopen() function.
The socket must be in blocking mode; it can have a timeout, but the fileobject’s internal buffer may end up in a inconsistent state if a timeoutoccurs.
Closing the file object returned bymakefile() won’t close theoriginal socket unless all other file objects have been closed andsocket.close() has been called on the socket object.
Note
On Windows, the file-like object created bymakefile() cannot beused where a file object with a file descriptor is expected, such as thestream arguments ofsubprocess.Popen().
Receive data from the socket. The return value is a bytes object representing thedata received. The maximum amount of data to be received at once is specifiedbybufsize. See the Unix manual pagerecv(2) for the meaning ofthe optional argumentflags; it defaults to zero.
Note
For best match with hardware and network realities, the value ofbufsizeshould be a relatively small power of 2, for example, 4096.
Receive data from the socket. The return value is a pair(bytes,address)wherebytes is a bytes object representing the data received andaddress is theaddress of the socket sending the data. See the Unix manual pagerecv(2) for the meaning of the optional argumentflags; it defaultsto zero. (The format ofaddress depends on the address family — see above.)
Receive normal data (up tobufsize bytes) and ancillary data fromthe socket. Theancbufsize argument sets the size in bytes ofthe internal buffer used to receive the ancillary data; it defaultsto 0, meaning that no ancillary data will be received. Appropriatebuffer sizes for ancillary data can be calculated usingCMSG_SPACE() orCMSG_LEN(), and items which do not fitinto the buffer might be truncated or discarded. Theflagsargument defaults to 0 and has the same meaning as forrecv().
The return value is a 4-tuple:(data,ancdata,msg_flags,address). Thedata item is abytes object holding thenon-ancillary data received. Theancdata item is a list of zeroor more tuples(cmsg_level,cmsg_type,cmsg_data) representingthe ancillary data (control messages) received:cmsg_level andcmsg_type are integers specifying the protocol level andprotocol-specific type respectively, andcmsg_data is abytes object holding the associated data. Themsg_flagsitem is the bitwise OR of various flags indicating conditions onthe received message; see your system documentation for details.If the receiving socket is unconnected,address is the address ofthe sending socket, if available; otherwise, its value isunspecified.
On some systems,sendmsg() andrecvmsg() can be used topass file descriptors between processes over anAF_UNIXsocket. When this facility is used (it is often restricted toSOCK_STREAM sockets),recvmsg() will return, in itsancillary data, items of the form(socket.SOL_SOCKET,socket.SCM_RIGHTS,fds), wherefds is abytes objectrepresenting the new file descriptors as a binary array of thenative Cint type. Ifrecvmsg() raises anexception after the system call returns, it will first attempt toclose any file descriptors received via this mechanism.
Some systems do not indicate the truncated length of ancillary dataitems which have been only partially received. If an item appearsto extend beyond the end of the buffer,recvmsg() will issueaRuntimeWarning, and will return the part of it which isinside the buffer provided it has not been truncated before thestart of its associated data.
On systems which support theSCM_RIGHTS mechanism, thefollowing function will receive up tomaxfds file descriptors,returning the message data and a list containing the descriptors(while ignoring unexpected conditions such as unrelated controlmessages being received). See alsosendmsg().
importsocket,arraydefrecv_fds(sock,msglen,maxfds):fds=array.array("i")# Array of intsmsg,ancdata,flags,addr=sock.recvmsg(msglen,socket.CMSG_LEN(maxfds*fds.itemsize))forcmsg_level,cmsg_type,cmsg_datainancdata:if(cmsg_level==socket.SOL_SOCKETandcmsg_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)])returnmsg,list(fds)
Availability: most Unix platforms, possibly others.
New in version 3.3.
Receive normal data and ancillary data from the socket, behaving asrecvmsg() would, but scatter the non-ancillary data into aseries of buffers instead of returning a new bytes object. Thebuffers argument must be an iterable of objects that exportwritable buffers (e.g.bytearray objects); these will befilled with successive chunks of the non-ancillary data until ithas all been written or there are no more buffers. The operatingsystem may set a limit (sysconf() valueSC_IOV_MAX)on the number of buffers that can be used. Theancbufsize andflags arguments have the same meaning as forrecvmsg().
The return value is a 4-tuple:(nbytes,ancdata,msg_flags,address), wherenbytes is the total number of bytes ofnon-ancillary data written into the buffers, andancdata,msg_flags andaddress are the same as forrecvmsg().
Example:
>>>importsocket>>>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.
Receive data from the socket, writing it intobuffer instead of creating anew bytestring. The return value is a pair(nbytes,address) wherenbytes isthe number of bytes received andaddress is the address of the socket sendingthe data. See the Unix manual pagerecv(2) for the meaning of theoptional argumentflags; it defaults to zero. (The format ofaddressdepends on the address family — see above.)
Receive up tonbytes bytes from the socket, storing the data into a bufferrather than creating a new bytestring. Ifnbytes is not specified (or 0),receive up to the size available in the given buffer. Returns the number ofbytes received. See the Unix manual pagerecv(2) for the meaningof the optional argumentflags; it defaults to zero.
Send data to the socket. The socket must be connected to a remote socket. Theoptionalflags argument has the same meaning as forrecv() above.Returns the number of bytes sent. Applications are responsible for checking thatall data has been sent; if only some of the data was transmitted, theapplication needs to attempt delivery of the remaining data. For furtherinformation on this topic, consult theSocket Programming HOWTO.
Send data to the socket. The socket must be connected to a remote socket. Theoptionalflags argument has the same meaning as forrecv() above.Unlikesend(), this method continues to send data frombytes untileither all data has been sent or an error occurs.None is returned onsuccess. On error, an exception is raised, and there is no way to determine howmuch data, if any, was successfully sent.
Send data to the socket. The socket should not be connected to a remote socket,since the destination socket is specified byaddress. The optionalflagsargument has the same meaning as forrecv() above. Return the number ofbytes sent. (The format ofaddress depends on the address family — seeabove.)
Send normal and ancillary data to the socket, gathering thenon-ancillary data from a series of buffers and concatenating itinto a single message. Thebuffers argument specifies thenon-ancillary data as an iterable of buffer-compatible objects(e.g.bytes objects); the operating system may set a limit(sysconf() valueSC_IOV_MAX) on the number of buffersthat can be used. Theancdata argument specifies the ancillarydata (control messages) as an iterable of zero or more tuples(cmsg_level,cmsg_type,cmsg_data), wherecmsg_level andcmsg_type are integers specifying the protocol level andprotocol-specific type respectively, andcmsg_data is abuffer-compatible object holding the associated data. Note thatsome systems (in particular, systems withoutCMSG_SPACE())might support sending only one control message per call. Theflags argument defaults to 0 and has the same meaning as forsend(). Ifaddress is supplied and notNone, it sets adestination address for the message. The return value is thenumber of bytes of non-ancillary data sent.
The following function sends the list of file descriptorsfdsover anAF_UNIX socket, on systems which support theSCM_RIGHTS mechanism. See alsorecvmsg().
importsocket,arraydefsend_fds(sock,msg,fds):returnsock.sendmsg([msg],[(socket.SOL_SOCKET,socket.SCM_RIGHTS,array.array("i",fds))])
Availability: most Unix platforms, possibly others.
New in version 3.3.
Set blocking or non-blocking mode of the socket: ifflag is false, thesocket is set to non-blocking, else to blocking mode.
This method is a shorthand for certainsettimeout() calls:
Set a timeout on blocking socket operations. Thevalue argument can be anonnegative floating point number expressing seconds, orNone.If a non-zero value is given, subsequent socket operations will raise atimeout exception if the timeout periodvalue has elapsed beforethe operation has completed. If zero is given, the socket is put innon-blocking mode. IfNone is given, the socket is put in blocking mode.
For further information, please consult thenotes on socket timeouts.
Set the value of the given socket option (see the Unix manual pagesetsockopt(2)). The needed symbolic constants are defined in thesocket module (SO_* etc.). The value can be an integer or abytes object representing a buffer. In the latter case it is up to the caller toensure that the bytestring contains the proper bits (see the optional built-inmodulestruct for a way to encode C structures as bytestrings).
Shut down one or both halves of the connection. Ifhow isSHUT_RD,further receives are disallowed. Ifhow isSHUT_WR, further sendsare disallowed. Ifhow isSHUT_RDWR, further sends and receives aredisallowed.
Duplicate a socket and prepare it for sharing with a target process. Thetarget process must be provided withprocess_id. The resulting bytes objectcan then be passed to the target process using some form of interprocesscommunication and the socket can be recreated there usingfromshare().Once this method has been called, it is safe to close the socket sincethe operating system has already duplicated it for the target process.
Availability: Windows.
New in version 3.3.
Note that there are no methodsread() orwrite(); userecv() andsend() withoutflags argument instead.
Socket objects also have these (read-only) attributes that correspond to thevalues given to thesocket constructor.
The socket family.
The socket type.
The socket protocol.
A socket object can be in one of three modes: blocking, non-blocking, ortimeout. Sockets are by default always created in blocking mode, but thiscan be changed by callingsetdefaulttimeout().
Note
At the operating system level, sockets intimeout mode are internally setin non-blocking mode. Also, the blocking and timeout modes are shared betweenfile descriptors and socket objects that refer to the same network endpoint.This implementation detail can have visible consequences if e.g. you decideto use thefileno() of a socket.
Theconnect() operation is also subject to the timeoutsetting, and in general it is recommended to callsettimeout()before callingconnect() or pass a timeout parameter tocreate_connection(). However, the system network stack may alsoreturn a connection timeout error of its own regardless of any Python sockettimeout setting.
Ifgetdefaulttimeout() is notNone, sockets returned bytheaccept() method inherit that timeout. Otherwise, thebehaviour depends on settings of the listening socket:
Here are four minimal example programs using the TCP/IP protocol: a server thatechoes all data that it receives back (servicing only one client), and a clientusing it. Note that a server must perform the sequencesocket(),bind(),listen(),accept() (possiblyrepeating theaccept() to service more than one client), while aclient only needs the sequencesocket(),connect(). Alsonote that the server does notsendall()/recv() onthe socket it is listening on but on the new socket returned byaccept().
The first two examples support IPv4 only.
# Echo server programimportsocketHOST=''# Symbolic name meaning all available interfacesPORT=50007# Arbitrary non-privileged ports=socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.bind((HOST,PORT))s.listen(1)conn,addr=s.accept()print('Connected by',addr)whileTrue:data=conn.recv(1024)ifnotdata:breakconn.sendall(data)conn.close()
# Echo client programimportsocketHOST='daring.cwi.nl'# The remote hostPORT=50007# The same port as used by the servers=socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.connect((HOST,PORT))s.sendall(b'Hello, world')data=s.recv(1024)s.close()print('Received',repr(data))
The next two examples are identical to the above two, but support both IPv4 andIPv6. The server side will listen to the first address family available (itshould listen to both instead). On most of IPv6-ready systems, IPv6 will takeprecedence and the server may not accept IPv4 traffic. The client side will tryto connect to the all addresses returned as a result of the name resolution, andsends traffic to the first one connected successfully.
# Echo server programimportsocketimportsysHOST=None# Symbolic name meaning all available interfacesPORT=50007# Arbitrary non-privileged ports=Noneforresinsocket.getaddrinfo(HOST,PORT,socket.AF_UNSPEC,socket.SOCK_STREAM,0,socket.AI_PASSIVE):af,socktype,proto,canonname,sa=restry:s=socket.socket(af,socktype,proto)exceptOSErrorasmsg:s=Nonecontinuetry:s.bind(sa)s.listen(1)exceptOSErrorasmsg:s.close()s=NonecontinuebreakifsisNone:print('could not open socket')sys.exit(1)conn,addr=s.accept()print('Connected by',addr)whileTrue:data=conn.recv(1024)ifnotdata:breakconn.send(data)conn.close()
# Echo client programimportsocketimportsysHOST='daring.cwi.nl'# The remote hostPORT=50007# The same port as used by the servers=Noneforresinsocket.getaddrinfo(HOST,PORT,socket.AF_UNSPEC,socket.SOCK_STREAM):af,socktype,proto,canonname,sa=restry:s=socket.socket(af,socktype,proto)exceptOSErrorasmsg:s=Nonecontinuetry:s.connect(sa)exceptOSErrorasmsg:s.close()s=NonecontinuebreakifsisNone:print('could not open socket')sys.exit(1)s.sendall(b'Hello, world')data=s.recv(1024)s.close()print('Received',repr(data))
The next example shows how to write a very simple network sniffer with rawsockets on Windows. The example requires administrator privileges to modifythe interface:
importsocket# the public network interfaceHOST=socket.gethostbyname(socket.gethostname())# create a raw socket and bind it to the public interfaces=socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_IP)s.bind((HOST,0))# Include IP headerss.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)# receive all packagess.ioctl(socket.SIO_RCVALL,socket.RCVALL_ON)# receive a packageprint(s.recvfrom(65565))# disabled promiscuous modes.ioctl(socket.SIO_RCVALL,socket.RCVALL_OFF)
The last example shows how to use the socket interface to communicate to a CANnetwork. This example might require special priviledge:
importsocketimportstruct# CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)can_frame_fmt="=IB3x8s"can_frame_size=struct.calcsize(can_frame_fmt)defbuild_can_frame(can_id,data):can_dlc=len(data)data=data.ljust(8,b'\x00')returnstruct.pack(can_frame_fmt,can_id,can_dlc,data)defdissect_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' interfaces=socket.socket(socket.AF_CAN,socket.SOCK_RAW,socket.CAN_RAW)s.bind(('vcan0',))whileTrue: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)exceptOSError:print('Error sending CAN frame')try:s.send(build_can_frame(0x01,b'\x01\x02\x03'))exceptOSError:print('Error sending CAN frame')
Running an example several times with too small delay between executions, couldlead to this error:
OSError:[Errno98]Addressalreadyinuse
This is because the previous execution has left the socket in aTIME_WAITstate, and can’t be immediately reused.
There is asocket 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))
theSO_REUSEADDR flag tells the kernel to reuse a local socket inTIME_WAIT state, without waiting for its natural timeout to expire.
See also
For an introduction to socket programming (in C), see the following papers:
both in the UNIX Programmer’s Manual, Supplementary Documents 1 (sectionsPS1:7 and PS1:8). The platform-specific reference material for the varioussocket-related system calls are also a valuable source of information on thedetails of socket semantics. For Unix, refer to the manual pages; for Windows,see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers maywant to refer toRFC 3493 titled Basic Socket Interface Extensions for IPv6.
18. Interprocess Communication and Networking
18.2.ssl — TLS/SSL wrapper for socket objects
Enter search terms or a module, class or function name.