Skip to main content

Socks

There is certainly some confusion with sockets, as my flatmate put it; sockets connect stuff together right?

Wikipedia puts it a little clearer with:
sockets are inter-process communication endpoints
That sounds pretty boring but I promise you can do some fairly interesting things with them. Sockets are a core part of the operating system, and a socket API is used to direct how the operating system should use sockets.

So the hello world of sockets would have to be an echo server. Let's create a basic Python3 socket server that will listen on IPv6 and repeat what it hears.

The Python Howto guide for sockets starts with this:
Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around.
On the server side, you follow these steps:
  1. Create a socket (possibly after querying the system for information)
  2. Bind the socket, which assigns the socket to an address
  3. Listen prepares it for incoming connections
  4. Accept an incoming connection from a client, giving you a new dedicated socket to communicate with that client.
Then the server can call send and recv on this new socket. Much like this:

#!/usr/bin/env python3
# Echo consumer_server program
import socket
import threading

host = "localhost"               # Symbolic name meaning all available interfaces
random_port = 50007              # Arbitrary non-privileged port

def echo(conn, addr):
    while True:
        data = conn.recv(1024)
        if not data: break
        print('Server heard "{}"'.format(data.decode()))
        conn.send(data)
    conn.close()

def consumer_server(address_family, socket_type, protocol, canonname, sa):
    try:
        s = socket.socket(address_family, socket_type, protocol)
    except OSError as msg:
        print(msg)
        print('could not open socket')
        return
    # Tell the OS it can reuse a socket if it wants
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        s.bind(sa)
        # tells the OS that we want it to queue up to 5 connect requests
        s.listen(5)
    except OSError as msg:
        s.close()
        raise SystemExit('Socket binding/listening failed...')

    while True:
        try:
            conn, addr = s.accept()
            print('Connected by', addr)
            threading.Thread(target=echo, args=(conn, addr)).start()
        except KeyboardInterrupt:
            s.close()
            raise SystemExit()

address_info = socket.getaddrinfo(host, random_port, 
                         socket.AF_UNSPEC, socket.SOCK_STREAM, 
                         0, socket.AI_PASSIVE)[-1]
consumer_server(*address_info)
Hopefully this server program is easy enough to understand, it is based very closely on the socket example in the Python documentation. My small alterations cause the server to listen only on IPv6, and will spin off a new thread when a client connects, and the server keeps listening for more connections. Part two of "Hello World in Sockets" is the client which follows a sequence of:
  1. Creating a socket (also using system information from getaddrinfo)
  2. connecting to the socket
Then the client can send, sendall, and recv bytes over the socket. Simple!

# Echo client program
import socket

HOST = 'localhost'    # The remote host
PORT = 50007          # The same port as used by the server

af, socktype, proto, _, sa = socket.getaddrinfo(HOST, 
                                                PORT, 
                                                socket.AF_UNSPEC, 
                                                socket.SOCK_STREAM)[0]

try:
    s = socket.socket(af, socktype, proto)
    s.connect(sa)
except socket.error:
    s.close()
    raise SystemExit('Error: Could not open socket :-/')

def send_and_receive(outgoing_data):
    s.sendall(outgoing_data)
    incoming_data = s.recv(1024)
    print('Received', incoming_data.decode())

for data in [b'Hello, world', '汉语/漢語 Hànyǔ'.encode()]:
    send_and_receive(data)

s.close()

That's the simple low level stuff out of the way! I'd like to point out that Python does have a higher level socket api that could easily implement our echo server, have a look at the TCP Socket examples that use the socketserver module. Now the stuff I'm really interested in, using sockets with Bluetooth and CAN!

Popular posts from this blog

Driveby contribution to Python Cryptography

While at PyConAU 2016 I attended the Monday sprints and spent some time looking at a proposed feature I hoped would soon be part of cryptography . As most readers of this blog will know, cryptography is a very respected project within the Python ecosystem and it was an interesting experience to see how such a prominent open source project handles contributions and reviews. The feature in question is the Diffie-Hellman Key Exchange algorithm used in many cryptography applications. Diffie-Helman Key Exchange is a way of generating a shared secret between two parties where the secret can't be determined by an eavesdropper observing the communication. DHE is extremely common - it is one of the primary methods used to provide "perfect forward secrecy" every time you initiate a TLS connection to an HTTPS website. Mathematically it is extremely elegant and the inventors were the recipients of the 2015 Turing award . I wanted to write about this particular contribution becau...

Matplotlib in Django

The official django tutorial is very good, it stops short of displaying data with matplotlib - which could be very handy for dsp or automated testing. This is an extension to the tutorial. So first you must do the official tutorial! Complete the tutorial (as of writing this up to part 4). Adding an image to a view To start with we will take a static image from the hard drive and display it on the polls index page. Usually if it really is a static image this would be managed by the webserver eg apache. For introduction purposes we will get django to serve the static image. To do this we first need to change the template. Change the template At the moment poll_list.html probably looks something like this: <h1>Django test app - Polls</h1> {% if object_list %} <ul> {% for object in object_list %} <li><a href="/polls/{{object.id}}">{{ object.question }}</a></li> {% endfor %} </ul> {% else %} <p>No polls...

Python and Gmail with IMAP

Today I had to automatically access my Gmail inbox from Python. I needed the ability to get an unread email count, the subjects of those unread emails and then download them. I found a Gmail.py library on sourceforge, but it actually opened the normal gmail webpage and site scraped the info. I wanted something much faster, luckily gmail can now be accessed with both pop and imap. After a tiny amount of research I decided imap was the better albiet slightly more difficult protocol. Enabling imap in gmail is straight forward, it was under labs. The address for gmail's imap server is: imap.gmail.com:993 Python has a library module called imaplib , we will make heavy use of that to access our emails. I'm going to assume that we have already defined two globals - username and password. To connect and login to the gmail server and select the inbox we can do: import imaplib imap_server = imaplib . IMAP4_SSL ( "imap.gmail.com" , 993 ) imap_server . login ( use...