Convert string IPv4 or IPv6 address to binary address as returned by get_bind_addrs. Very naive implementation that certainly doesn't work for all IPv6 variants.
(addr)
| 113 | for i in range(0, outbytes, struct_size)] |
| 114 | |
| 115 | def addr_to_hex(addr): |
| 116 | ''' |
| 117 | Convert string IPv4 or IPv6 address to binary address as returned by |
| 118 | get_bind_addrs. |
| 119 | Very naive implementation that certainly doesn't work for all IPv6 variants. |
| 120 | ''' |
| 121 | if '.' in addr: # IPv4 |
| 122 | addr = [int(x) for x in addr.split('.')] |
| 123 | elif ':' in addr: # IPv6 |
| 124 | sub = [[], []] # prefix, suffix |
| 125 | x = 0 |
| 126 | addr = addr.split(':') |
| 127 | for i,comp in enumerate(addr): |
| 128 | if comp == '': |
| 129 | if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end |
| 130 | continue |
| 131 | x += 1 # :: skips to suffix |
| 132 | assert(x < 2) |
| 133 | else: # two bytes per component |
| 134 | val = int(comp, 16) |
| 135 | sub[x].append(val >> 8) |
| 136 | sub[x].append(val & 0xff) |
| 137 | nullbytes = 16 - len(sub[0]) - len(sub[1]) |
| 138 | assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) |
| 139 | addr = sub[0] + ([0] * nullbytes) + sub[1] |
| 140 | else: |
| 141 | raise ValueError('Could not parse address %s' % addr) |
| 142 | return hexlify(bytearray(addr)).decode('ascii') |
| 143 | |
| 144 | def test_ipv6_local(): |
| 145 | ''' |