IP address to binary conversion

Rikard Bosnjakovic bos at hack.org
Wed Jun 13 19:58:50 EDT 2001


Jeroen Wolff wrote:

> Can somebody help me (a newbee) to convert an ip address to is 32 bits
> representation?

Lucky you, I had exactly that problem yesterday and hacked this
solution:


------------------[snip]------------------
import socket, struct

# return true if a string could be a pure ip address (4 dotted)
def is_ipaddress(str):
    if str.count(".") != 3:
        return 0
    for i in str.split("."):
        if not i.isdigit():
            return 0
        i = int(i)
        if i>255 or i<0:
            return 0
    return 1

def interpret_addr(str):
    host = None
    if is_ipaddress(str):
        res = socket.inet_aton(str)
    else:
        try:
            host = socket.gethostbyname(str)
        except:
            print "Can't resolve '%s'" %(str)
            return 0

    if host:
        res = socket.inet_aton(host)

    res = struct.unpack("!l", res)[0]

    if res == -1:
        return 0

    return res

>>> interpret_addr("10.30.40.50")
169748530
>>> interpret_addr("www.hotmail.com")
1074015239
------------------[snip]------------------




--
Rikard Bosnjakovic - http://bos.hack.org/cv/ - ICQ: 1158217

Anyone sending unwanted advertising e-mail to my address will be
charged $250 for network traffic and computing time. By extracting my
address from this message or its header, you agree to these terms.



More information about the Python-list mailing list