Python Script: IP Address to 10digit decimal to IP address

Friday, November 30, 2012 Posted by Unknown 1 comments
When hacking android apps I learned today that you can convert a IP address into a 10digit decimal number. This number is still valid in any web browser. I wrote two python programs to go both ways ;)

Used http://www.iowight.com/iwindex/decimal.php3 for the math.

From 10digit decimal to ip address:


#convert 10digit decimal formated ipaddress to normal ipaddress
#by init6
#blog.init6.me

import sys

def main():
    #read file and convert each line to ip address. Comment out to ask for input.
    with open('c:\ipaddress.txt', 'r') as infile:
        for line in infile:
            print (convert(int(line)))
    infile.close()

    #ask for input (dec format) Uncomment to ask for input.
    #decIn = input("Enter 10 digit decimal formated ipaddress: ")
    
def convert(decIn):

    if is32(decIn) == True:
        #convert dec to hex
        fullHex = hex(decIn).lstrip("0x")

        #Split hex number into four pairs
        hex1 = fullHex[0:2]
        hex2 = fullHex[2:4]
        hex3 = fullHex[4:6]
        hex4 = fullHex[6:8]
        #Convert each hex to decimal then to a string and return ip address.
        ipAddr = ( str(int(hex1,16)) + '.' + str(int(hex2,16)) + '.' + str(int(hex3,16)) + '.' + str(int(hex4,16)) )
        return ipAddr
    
#Checks to see if input is a 32bit int or less to make sure its a vaild ip address.         
def is32(n):
    try:
        bitstring=bin(n)
    except (TypeError, ValuueError):
        return False

    if len(bin(n)[2:]) <= 32:
        return True
    else:
        print ("Not a vaild 32bit 10 digit decimal")
        return False
    
main()


From IP Address to 10 digit decimal.


#convert ip address to a 10digit decimal formated ipaddress.
#by init6
#blog.init6.me

import sys

def main():
    ipAddr = raw_input("Type in IP Address to convert to 10digit decimal: ")
    print ( convert(ipAddr) )

def convert(ipAddr):
    out = ipAddr.split('.')
    octets = [int(out[0]), int(out[1]), int(out[2]), int(out[3])]
    hexNum = '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
    return int(hexNum, 16)

main()
Labels: , ,

UPDATE: CMYIP

Thursday, November 29, 2012 Posted by Unknown 0 comments
cmyip.com changed the way they encoded the numbers so I could no longer pull the ip address directly from the source code. Instead of trying to decode the htmlnumbers to ascii not only because its hard but they have it setup to change the encoding. So now, Grab the source code and feed it through w3m browser and dump it back out to the terminal then grep the IP Address.

http://pastie.org/5454850


#!/bin/bash
ip_addr=`curl -s http://cmyip.com | w3m -T text/html -dump | grep -o -E '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'`
echo $ip_addr
Labels: