我有一個小問題,我的腳本,我需要將表單'xxx.xxx.xxx.xxx'中的IP轉換爲整數表示,並從此表單返回。從IP字符串轉換爲整數,並在Python中向後
def iptoint(ip):
return int(socket.inet_aton(ip).encode('hex'),16)
def inttoip(ip):
return socket.inet_ntoa(hex(ip)[2:].decode('hex'))
In [65]: inttoip(iptoint('192.168.1.1'))
Out[65]: '192.168.1.1'
In [66]: inttoip(iptoint('4.1.75.131'))
---------------------------------------------------------------------------
error Traceback (most recent call last)
/home/thc/<ipython console> in <module>()
/home/thc/<ipython console> in inttoip(ip)
error: packed IP wrong length for inet_ntoa`
任何人都知道如何解決這個問題?
在我的Python 2.6.6中完全不起作用:'inttoip'引發'TypeError:奇數長度的字符串'。 – Ilkka 2011-04-11 10:15:27
@Ilkka對inttoip使用socket.inet_ntoa(hex(ip)[2:]。decode('hex')) – 2015-01-21 12:00:32