#!/usr/bin/env python
# coding: utf-8

import errno, socket, sys, time
from subprocess import getoutput

def server(port, reuseport=True):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if reuseport:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    s.bind(('127.0.0.1', port))
    s.listen(1)
    return s

def connect(port, blocking=True):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setblocking(blocking)
    try:
        s.connect(('127.0.0.1', port))
    except socket.error as e:
        # For non-blocking sockets, EINPROGRESS is expected.
        if not blocking and e.errno == errno.EINPROGRESS:
            pass
        else:
            raise
    return s

def main():
    p = 12346
    i = 0
    while True:
        srv = server(p, True)
        cli = connect(p, False)
        c, _ = srv.accept()

        c.close()
        cli.close()
        srv.close()

        i += 1
        if i % 50 == 0:
            try:
                n = getoutput('jq -r \".cidr_rules | length\" < /dev/syd').strip()
            except:
                n = '?'
            sys.stderr.write("\r\033[K%d (rules: %s)" % (i, n))

if __name__ == '__main__':
    main()
