How to monitor IP address with python in hexadecimal?

Asked By 0 points N/A Posted on -
qa-featured

I use a PXE booted Linux machine. I need monitoring the IP address in hexadecimal format.

How to monitor IP address with python?

I need a python script that can output IP addresses in hexadecimal?

Please help me.

SHARE
Best Answer by nilenio
Answered By 0 points N/A #157805

How to monitor IP address with python in hexadecimal?

qa-featured

Hi

If you are using a PXE booted Linux machine. Sometimes you need to IP address in hexadecimal format. Given Python script will output the hexadecimal format for IP Addresses .

 

Best Answer
Best Answer
Answered By 0 points N/A #157806

How to monitor IP address with python in hexadecimal?

qa-featured

Hello,

Try this out:

Import re
Import says
Import socket

If (not Len (sis. argv) == 2):
    Print "Usage: ip2hex. By hostname|IP address/mask"
    sys. Exit (1)

Try:
    (in_str, mask) = sys.argv[1].split("/")
    # sanity checks mask
    Mask = int (mask)
    If (mask > 32 or mask < 0):
        Print "Mask out of range"
        sys.exit(1)
Except ValueError:
    Mask = 0
    in_str = sys.argv[1]

Try:
    ip_addr = socket. gethostbyname (in_str)
Except:
    Print "Invalid address!"
    sys.exit(1)

#gethostbyname really checks this for us, but you never know
ip_regex = re.compile('(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).' 
                      '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).' 
                      '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).' 
                      '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)')
ip_match = ip_regex.match(ip_addr)

If (ip_match == None):
    Print "Invalid address"
    sys.exit(1)

hex_ip_addr = 0
For I in range (1,5):
    hex_ip_addr += int(ip_match.group(i)) << (4-i)*8

fmt = "%%0%dX" % ((32 - mask) / 4)
Print format % (hex_ip_addr >> mask)

Login/Register to Answer

Related Questions