在 Python 中将“little endian”十六进制字符串转换为 IP 地址

新手上路,请多包涵

将这种形式的字符串转换为 IP 地址的最佳方法是什么: "0200A8C0" 。字符串中的“八位字节”顺序相反,即给定的示例字符串应生成 192.168.0.2

原文由 Matt Joiner 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 874
2 个回答

网络地址操作由套接字模块提供。

socket.inet_ntoa(packed_ip)

将 32 位压缩 IPv4 地址(长度为四个字符的字符串)转换为其标准的点分四组字符串表示形式(例如,’123.45.67.89’)。这在与使用标准 C 库并需要 struct in_addr 类型对象的程序对话时很有用,该类型是此函数作为参数的 32 位打包二进制数据的 C 类型。

您可以将十六进制字符串转换为 packed ip 使用 struct.pack() 和小端,无符号长格式。

 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'

原文由 gimel 发布,翻译遵循 CC BY-SA 4.0 许可协议

>>> 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

原文由 Roger Pate 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题