Python Forum

Full Version: Hex-STRING to ip address
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

facing difficulties, below is my snmpwalk output, need to convert hex-string to IP address

[inline]SNMPv2-SMI::experimental.37.1.6.1.1.6.1.2.1 = Hex-STRING: 17 20 16 00 00 01
SNMPv2-SMI::experimental.37.1.6.1.1.6.1.3.1 = Hex-STRING: 17 20 19 00 01 29
SNMPv2-SMI::experimental.37.1.6.1.1.6.1.4.1 = Hex-STRING: 17 20 16 00 42 23
SNMPv2-SMI::experimental.37.1.6.1.1.6.1.5.1 = Hex-STRING: 17 20 18 00 00 01
SNMPv2-SMI::experimental.37.1.6.1.1.6.1.6.1 = Hex-STRING: 17 20 19 00 00 02
SNMPv2-SMI::experimental.37.1.6.1.1.6.1.7.1 = Hex-STRING: 17 20 19 00 12 23
SNMPv2-SMI::experimental.37.1.6.1.1.6.1.8.1 = Hex-STRING: 17 20 16 00 72 23
SNMPv2-SMI::experimental.37.1.6.1.1.6.1.12.1 = Hex-STRING: 17 20 19 00 00 01 [/inline]

expected output is
Output:
172.16.0.1 172.19.0.129 172.16.4.223 172.18.0.1 172.19.0.2
what have you tried so far?
Larz60+ (older and wiser),

I am thinking, not yet started, i though there might any module to convert this? i will definitely buzz you, if i not succeed.


regards
Anna
I did not understand until yet, how they have encoded the address as Hex-String. It's not a packed IPv4 address.

Edit: Oh the pattern is very easy. After the first coffee I got it.

def hex2ip(hexstr):
    """
    Can parse strings in this form:
    17 20 16 00 00 01
    """
    hexstr = hexstr.replace(' ', '')
    blocks = (''.join(block) for block in zip(*[iter(hexstr)]*3))
    blocks = (int(block) for block in blocks)
    return '.'.join(str(block) for block in blocks)
It's a bit of black magic inside.