尝试使用ctypes格式化ipv6字符串

时间:2013-12-31 20:23:54

标签: python ipv6

我无法将ipv6地址格式化为压缩二进制字符串。在进行一些挖掘后,似乎socket.inet_pton(...)在Windows中不起作用。在挖掘时,我遇到了使用ctypes和Ws2_32.dll中内置的InetPton函数的建议。下面是我的简单脚本:

import ctypes
import socket

a = ctypes.WinDLL("ws2_32.dll") 

in_addr_p = ctypes.create_string_buffer("200f::")
out_addr_p = ctypes.create_string_buffer(40)

a.inet_pton(socket.AF_INET6, in_addr_p, out_addr_p)
print "Input: {}".format(repr(in_addr_p.raw))
print "Output: {}".format(repr(out_addr_p.raw))

当我运行它时,我得到以下内容:

Input: '200f::\x00'
Output: ' \x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00\x00

我很难过为什么看起来“F”是唯一通过转换过程的角色。 “

1 个答案:

答案 0 :(得分:4)

' \x0f...'开头看到那个空格?这就是'20'结束的地方,因为\x20被渲染为空格。所以你的代码工作得很好......

如果您使用的是python3.3或更高版本,则应考虑使用ipaddress模块进行此类操作。 python2也应该有backports