[英]Convert "little endian" hex string to IP address in Python
將這種形式的字符串轉換為 IP 地址的最佳方法是什么: "0200A8C0"
。 字符串中的“八位字節”順序相反,即給定的示例字符串應生成192.168.0.2
。
網絡地址操作由套接字模塊提供。
將 32 位打包 IPv4 地址(長度為四個字符的字符串)轉換為其標准的點分四線字符串表示形式(例如,'123.45.67.89')。 這在與使用標准 C 庫並需要 struct in_addr 類型的對象進行對話時非常有用,該對象是此函數作為參數的 32 位打包二進制數據的 C 類型。
您可以使用struct.pack()
和小端無符號長格式將十六進制字符串轉換為packed ip
。
s = "0200A8C0"
import socket
import struct
addr_long = int(s, 16)
print(hex(addr_long)) # '0x200a8c0'
print(struct.pack("<L", addr_long)) # '\xc0\xa8\x00\x02'
print(socket.inet_ntoa(struct.pack("<L", addr_long))) # '192.168.0.2'
>>> s = "0200A8C0"
>>> bytes = ["".join(x) for x in zip(*[iter(s)]*2)]
>>> bytes
['02', '00', 'A8', 'C0']
>>> bytes = [int(x, 16) for x in bytes]
>>> bytes
[2, 0, 168, 192]
>>> print ".".join(str(x) for x in reversed(bytes))
192.168.0.2
它簡短而清晰; 將其包裝在一個帶有錯誤檢查功能的函數中以滿足您的需求。
方便的分組功能:
def group(iterable, n=2, missing=None, longest=True):
"""Group from a single iterable into groups of n.
Derived from http://bugs.python.org/issue1643
"""
if n < 1:
raise ValueError("invalid n")
args = (iter(iterable),) * n
if longest:
return itertools.izip_longest(*args, fillvalue=missing)
else:
return itertools.izip(*args)
def group_some(iterable, n=2):
"""Group from a single iterable into groups of at most n."""
if n < 1:
raise ValueError("invalid n")
iterable = iter(iterable)
while True:
L = list(itertools.islice(iterable, n))
if L:
yield L
else:
break
你可以這樣做:
>>> s = '0200A8C0'
>>> octets = [s[i:i+2] for i in range(0, len(s), 2)]
>>> ip = [int(i, 16) for i in reversed(octets)]
>>> ip_formatted = '.'.join(str(i) for i in ip)
>>> print ip_formatted
192.168.0.2
八位字節拆分可能可以更優雅地完成,但我想不出更簡單的方法。
編輯:或在一行上:
>>> s = '0200A8C0'
>>> print '.'.join(str(int(i, 16)) for i in reversed([s[i:i+2] for i in range(0, len(s), 2)]))
192.168.0.2
我的嘗試:
a = '0200A8C0'
indices = range(0, 8, 2)
data = [str(int(a[x:x+2], 16)) for x in indices]
'.'.join(reversed(data))
你可以做一個簡單的 def 從十六進制轉換為十進制 ip:
def hex2ip(iphex):
ip = ["".join(x) for x in zip(*[iter(str(iphex))]*2)]
ip = [int(x, 16) for x in ip]
ip = ".".join(str(x) for x in (ip))
return ip
# And to use it:
ip = "ac10fc40"
ip = hex2ip(iphex)
print(ip)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.