selfboot / AnnotatedShadowSocks

Annotated shadowsocks(python version)
Other
3 stars 1 forks source link

Convert between packed IPv6 & IPv4 address and its string representation. #9

Open selfboot opened 7 years ago

selfboot commented 7 years ago

snippet

def inet_ntop(family, ipstr):
    if family == socket.AF_INET:
        return to_bytes(socket.inet_ntoa(ipstr))
    elif family == socket.AF_INET6:
        import re
        v6addr = ':'.join(('%02X%02X' % (ord(i), ord(j))).lstrip('0')
                          for i, j in zip(ipstr[::2], ipstr[1::2]))
        v6addr = re.sub('::+', '::', v6addr, count=1)
        return to_bytes(v6addr)

Convert a packed IPv4 or IPv6 address to its string representation. Note: When convert a ipv6 address, you should make sure the ipstr is at most 128-bit, or you will not get error info.

Usage

>>> inet_ntop(socket.AF_INET6, b'1234123412341234')
'3132:3334:3132:3334:3132:3334:3132:3334'

IPv6 Address

In one IPv6 packet, the IPv6 address was represented by 128 bits. To be friendly to human, the 128 bits of an IPv6 address are represented in 8 groups of 16 bits each. Each group is written as four hexadecimal digits and the groups are separated by colons (:). An example of this representation is 2001:0db8:0000:0000:0000:ff00:0042:8329.

image

For convenience, an IPv6 address may be abbreviated to shorter notations by application of the following rules.

  1. One or more leading zeroes from any groups of hexadecimal digits are removed; this is usually done to either all or none of the leading zeroes. For example, the group 0042 is converted to 42.
  2. Consecutive sections of zeroes are replaced with a double colon (::). The double colon may only be used once in an address, as multiple use would render the address indeterminate.

An example of application of these rules:

Initial address: 2001:0db8:0000:0000:0000:ff00:0042:8329
After removing all leading zeroes in each group: 2001:db8:0:0:0:ff00:42:8329
After omitting consecutive sections of zeroes: 2001:db8::ff00:42:8329

The loopback address, 0000:0000:0000:0000:0000:0000:0000:0001, may be abbreviated to ::1 by using both rules.

Ref:
Wiki: IPv6
Use str.join with generator expression in python