Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created January 11, 2012 15:16
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save cslarsen/1595135 to your computer and use it in GitHub Desktop.
Save cslarsen/1595135 to your computer and use it in GitHub Desktop.
Two small Python functions to convert IPv4 address to integer and vice-versa
#!/usr/bin/env python
"""Functions to convert IPv4 address to integer and vice-versa.
Written by Christian Stigen Larsen, http://csl.sublevel3.org
Placed in the public domain by the author, 2012-01-11
Example usage:
$ ./ipv4 192.168.0.1 3232235521
192.168.0.1 ==> 3232235521
3232235521 ==> 192.168.0.1
"""
import sys
def from_string(s):
"Convert dotted IPv4 address to integer."
return reduce(lambda a,b: a<<8 | b, map(int, s.split(".")))
def to_string(ip):
"Convert 32-bit integer to dotted IPv4 address."
return ".".join(map(lambda n: str(ip>>n & 0xFF), [24,16,8,0]))
if __name__ == "__main__":
if len(sys.argv) <= 1:
print "Usage: ipv4 [ (address | integer)* ]"
print "Converts between IPv4 addresses and integers."
print ""
print "Example usage:"
print "$ ./ipv4 192.168.0.1 3232235521"
print "192.168.0.1 ==> 3232235521"
print "3232235521 ==> 192.168.0.1"
print ""
print "Written by Christian Stigen Larsen, http://csl.sublevel3.org"
print "Placed in the public domain by the author, 2012-01-11"
sys.exit(0)
for arg in sys.argv[1:]:
if arg.count(".") == 3:
print arg, "==>", from_string(arg)
else:
try:
print arg, "==>", to_string(int(arg))
except Exception, e:
print "Not an integer or dotted IPv4 address:", arg
sys.exit(1)
@cslarsen
Copy link
Author

cslarsen commented Nov 7, 2012

If you're looking for more IP-handling for Python, check out Google's code at http://code.google.com/p/ipaddr-py/source/browse/trunk/ipaddr.py

@cizixs
Copy link

cizixs commented Jul 24, 2014

So brilliant! saved my day.

@st4rry
Copy link

st4rry commented Apr 25, 2018

Awesome !!! You saved my day.

@erwinkinn
Copy link

As I quite remember there was the stdlib's module ipaddress :)
So, you just had to write

import ipaddress
ip = ipaddress.IPv4Address("192.168.0.1")
print(int(ip))
print(str(ip))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment