import socket def int16(x): x = int(x) return x.to_bytes(2, 'big') def int24(x): x = int(x) return x.to_bytes(3, 'big') def int32(x): x = int(x) return x.to_bytes(4, 'big') def inet_aton(addr): dots = addr.count('.') if dots == 2: # a.b.c a_b, c = addr.rsplit('.', 1) a_b = socket.inet_pton(socket.AF_INET, a_b + '.0.0') return a_b[:2] + int16(c) elif dots == 1: # a.b a, b = addr.rsplit('.', 1) a = socket.inet_pton(socket.AF_INET, a + '.0.0.0') return a[:1] + int24(b) elif dots == 0: # a (32 bits) return int32(addr) else: # Expect a.b.c.d format return socket.inet_pton(socket.AF_INET, addr) def test(addr): b = socket.inet_aton(addr) a = inet_aton(addr) assert a == b, (a, b) test('127.0.0.1') test('127.0.65535') test('127.16777215') test('4294967295')