Socket

python documentation

Anonymous

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

Programmers have a number of third-party tools to create networked servers and clients in Python, but the core module for all of those tools is socket

I’ve added the flow that is analogus to regular files to understand the parts of sockets and they’re very similar to files, dispite python being slightly different interface in the socket library.

Python
import socket

target_host = "www.google.ca"
target_port = 80

# ---- Open() basically, setup and config
# Create a socket object (ipv4)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the client
client.connect((target_host, target_port))

# ---- Write()
# send some data
client.send(b"GET ? HTTP/1.1\r\nHost: google.com\r\n\r\n")

# ---- Read()
# recieve some data
response = client.recv(4096)
print(response.decode())

# ---- Close()
# Close the fd for the socket
client.close()

Closing sockets

Sockets are just fire descriptors. What do you do when you’re done with a fd? You close them? Although same as all other fds they’re closed when the parent process is it closed, it’s best practice to defer them to be closed once they’re open.

Python
        # Try/catch so we can handle SIGINT
        try:
            while True:
                ...
        except KeyboardInterrupt:
            print('User terminated.')
        finally:
            self.socket.close()