The socket Module

The socket module supplies a factory function, also named socket, that you call to generate a socket object s. To perform network operations, call methods on s. In a client program, connect to a server by calling s.connect. In a server program, wait for clients to connect by calling s.bind and s.listen. When a client requests a connection, accept the request by calling s.accept, which returns another socket object s1 connected to the client. Once you have a connected socket object, transmit data by calling its method send and receive data by calling its method recv.

Python supports both current Internet Protocol (IP) standards. IPv4 is more widespread; IPv6 is newer. In IPv4, a network address is a pair (host,port). host is a Domain Name System (DNS) hostname such as 'www.python.org' or a dotted-quad IP address such as '194.109.137.226'. port is an integer that indicates a socket’s port number. In IPv6, a network address is a tuple (host,port,flowinfo,scopeid). IPv6 infrastructure is not yet widely deployed; I do not cover IPv6 further in this book. When host is a DNS hostname, Python looks up the name on your platform’s DNS infrastructure, using the IP address that corresponds to the name.

Module socket supplies an exception class error. Functions and methods of socket raise error to diagnose socket-specific errors. Module socket also supplies many functions. Many of these functions translate data, such as integers, between your host’s native format and network ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.