python ipv4/ipv6字符串和整型互转

ipv4/ipv6字符串和整型互转

import socket
import struct

def ipv4_str_to_int(ip_str):
    return struct.unpack('!I', socket.inet_pton(socket.AF_INET, ip_str))[0]

def ipv4_int_to_str(ip_int):
    ip_pack = struct.pack('!I', ip_int)
    return socket.inet_ntop(socket.AF_INET, ip_pack)

def ipv6_str_to_int(ip):
    hi, lo = struct.unpack('!QQ', socket.inet_pton(socket.AF_INET6, ip))
    return ((hi << 64) | lo)

def ipv6_int_to_str(ip_int):
    hi = (ip_int >> 64) & 0xFFFFFFFFFFFFFFFF;
    lo = ip_int & 0xFFFFFFFFFFFFFFFF
    ip_pack = struct.pack('!QQ', hi, lo)
    return socket.inet_ntop(socket.AF_INET6, ip_pack)

if __name__ == '__main__':
    #case 1
    print("ipv6: abcd:5678::1234 int: %x" %ipv6_str_to_int("abcd:5678::1234"))
    print(ipv6_int_to_str(ipv6_str_to_int("abcd:5678::1234")))

    #case 2
    ipv4 = "192.168.100.101"
    print("ipv4: 192.168.100.101 int: %x" %ipv4_str_to_int(ipv4))
    print(ipv4_int_to_str(ipv4_str_to_int(ipv4)))

说明:
socket.inet_pton 这个函数返回的是结构化数据

你可能感兴趣的:(python,入门,网络,python)