Skip to content

Instantly share code, notes, and snippets.

@vnetman
Created April 25, 2018 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vnetman/9ea2138b1e64aa7b19090d8083733e00 to your computer and use it in GitHub Desktop.
Save vnetman/9ea2138b1e64aa7b19090d8083733e00 to your computer and use it in GitHub Desktop.
Convert an IPv4 address in standard (dotted decimal) notation to a decimal number, for educational/entertainment purposes
#!/usr/bin/env python3
#
# Convert an IPv4 address in standard (dotted decimal) notation to a
# decimal number, for educational/entertainment purposes
# .
#
# E.g.
#
# vnetman@vnetman-laptop:~/data/bin$ ./ipv4.py
# Usage: ./ipv4.py <ipv4 address>
#
# vnetman@vnetman-laptop:~/data/bin$ ./ipv4.py 8.8.4.4
# 134743044, 0x8080404
#
# vnetman@vnetman-laptop:~/data/bin$ ping -c 3 134743044
# PING 134743044 (8.8.4.4) 56(84) bytes of data.
# 64 bytes from 8.8.4.4: icmp_seq=1 ttl=58 time=12.1 ms
# 64 bytes from 8.8.4.4: icmp_seq=2 ttl=58 time=12.0 ms
# 64 bytes from 8.8.4.4: icmp_seq=3 ttl=58 time=12.1 ms
#
# --- 134743044 ping statistics ---
# 3 packets transmitted, 3 received, 0% packet loss, time 2002ms
# rtt min/avg/max/mdev = 12.087/12.132/12.186/0.098 ms
# vnetman@vnetman-laptop:~/data/bin$
#
import sys
import re
if len(sys.argv) != 2:
print('Usage: {} <ipv4 address>'.format(sys.argv[0]))
sys.exit(-1)
user_ip = sys.argv[1]
# Parse dotted decimal to individual octets
re_ip_addr = re.compile(r'^(\d{1,3}).(\d{1,3}).(\d{1,3}).(\d{1,3})$')
octets = re_ip_addr.findall(user_ip)
if not octets:
print('"{}" is not a valid IPv4 address'.format(user_ip))
sys.exit(-1)
sum = 0
shift = 24
for ostr in octets[0]:
o = int(ostr)
if ((o > 255) or (o < 0)):
print('"{}" is not a valid IPv4 address'.format(user_ip))
sys.exit(-1)
sum = sum + (o << shift)
shift = shift - 8
print('{}, {}'.format(str(sum), hex(sum)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment