Conversion from IP string to integer, and backward in Python

后端 未结 11 842
囚心锁ツ
囚心锁ツ 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 22:53

    It can be done without using any library.

    def iptoint(ip):
            h=list(map(int,ip.split(".")))
            return (h[0]<<24)+(h[0]<<16)+(h[0]<<8)+(h[0]<<0)
    
    def inttoip(ip):
           return ".".join(map(str,[((ip>>24)&0xff),((ip>>16)&0xff),((ip>>8)&0xff),((ip>>0)&0xff)]))
    
    iptoint("8.8.8.8") # 134744072
    
    inttoip(134744072) # 8.8.8.8
    

提交回复
热议问题