socket

Table of Contents

Exceptions and Errors

To get the detailed descriptions for errors you should use errno module

Wait until a host starts listening howto

from contextlib import closing
from socket import socket, AF_INET, SOCK_STREAM
from time import sleep

def wait_healthy(host, port, interval=1.):
    while True:
        with closing(socket(AF_INET, SOCK_STREAM)) as s:
            if s.connect_ex((host, port)) == 0:
                break
            else:
                sleep(interval)

Pick a free port number howto

from socket import socket, AF_INET, SOCK_STREAM
from contextlib import closing

def free_port():
    with closing(socket(AF_INET, SOCK_STREAM)) as s:
        s.bind(('localhost', 0))
        return s.getsockname()[1]