Many programming languages use sockets to communicate across processes or between devices. This topic explains proper usage the the sockets module in Python to facilitate sending and receiving data over common networking protocols.
Multi-threaded TCP Socket Server
When run with no arguments, this program starts a TCP socket server that listens for connections to 127.0.0.1 on port 5000. The server handles each connection in a separate thread.
When run with the -c argument, this program connects to the server, reads the client list, and prints it out. The client list is transferred as a JSON string. The client name may be specified by passing the -n argument. By passing different names, the effect on the client list may be observed.
The receive buffers are limited to 1024 bytes. If the JSON string representation of the client list exceeds this size, it will be truncated. This will cause the following exception to be raised:
Raw Sockets on Linux
First you disable your network card's automatic checksumming:
Then send your packet, using a SOCK_RAW socket:
Receiving data via UDP
UDP is a connectionless protocol. This means that peers sending messages do not require establishing a connection before sending messages. socket.recvfromthus returns a tuple (msg [the message the socket received], addr [the address of the sender])
A UDP server using solely the socket module:
Below is an alternative implementation using socketserver.UDPServer:
By default, sockets block. This means that execution of the script will wait until the socket receives data.
Sending data via TCP
Sending data over the internet is made possible using multiple modules. The sockets module provides low-level access to the underlying Operating System operations responsible for sending or receiving data from other computers or processes.
The following code sends the byte string b'Hello' to a TCP server listening on port 6667 on the host localhost and closes the connection when finished:
Socket output is blocking by default, that means that the program will wait in the connect and send calls until the action is 'completed'. For connect that means the server actually accepting the connection. For send it only means that the operating system has enough buffer space to queue the data to be send later.
Sockets should always be closed after use.
Sending data via UDP
UDP is a connectionless protocol. Messages to other processes or computers are sent without establishing any sort of connection. There is no automatic confirmation if your message has been received. UDP is usually used in latency sensitive applications or in applications sending network wide broadcasts.
The following code sends a message to a process listening on localhost port 6667 using UDP
Note that there is no need to "close" the socket after the send, because UDP is connectionless.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0