Conversion from IP string to integer, and backward in Python

后端 未结 11 877
囚心锁ツ
囚心锁ツ 2020-12-07 22:34

i have a little problem with my script, where i need to convert ip in form \'xxx.xxx.xxx.xxx\' to integer representation and go back from this form.

def ipto         


        
11条回答
  •  醉话见心
    2020-12-07 23:09

    #!/usr/bin/env python
    import socket
    import struct
    
    
    def ip2int(addr):
        return struct.unpack("!I", socket.inet_aton(addr))[0]
    
    
    def int2ip(addr):
        return socket.inet_ntoa(struct.pack("!I", addr))
    
    
    print(int2ip(0xc0a80164)) # 192.168.1.100
    print(ip2int('10.0.0.1')) # 167772161
    

提交回复
热议问题