python ip地址转换

import socket, struct
def ip2long(ip):  
    return struct.unpack("!L",socket.inet_aton(ip))[0]  
def long2ip(longip):  
    return socket.inet_ntoa(struct.pack('!L', longip))  
if __name__ == '__main__':  
    print('local ip address to long is %s'%ip2long('8.8.8.8'))  
    print('local ip address long to ip is %s'%long2ip(3756947712))  
    print('local ip address long to ip is %s'%long2ip(3756947967))  

结果如下:

local ip address to long is 134744072
local ip address long to ip is 223.238.121.0
local ip address long to ip is 223.238.121.255

你可能感兴趣的:(python ip地址转换)