【问题标题】:Byte-encoding IP address in Python 3 and converting back to stringPython 3中的字节编码IP地址并转换回字符串
【发布时间】:2018-03-31 02:38:00
【问题描述】:

我正在尝试在 Python3 中创建示例 UDP 数据包头:

# "encoding"
header = bytearray()
ip = '192.168.1.1'
ip_bytes = bytes(map(int, ip.split('.')))
header.extend(ip_bytes)
port = 5555    
header.extend(port.to_bytes(2, 'big'))
print(header)
print()

# "decoding"
destip = header[:4]
ips = ""
for i in destip:
    byt = int.from_bytes(destip[i:i+1], 'big')
    ips += str(byt) + "."
ips = ips[:len(ips)-1]
print(ips)

输出是:

bytearray(b'\xc0\xa8\x01\x01\x15\xb3')

bytearray(b'\xc0\xa8\x01\x01')
0.0.168.168

我想要的是第二行是:

192.168.1.1

有人知道我哪里出错了吗?

【问题讨论】:

标签: python-3.x networking udp ip


【解决方案1】:

不要将 ip_arg 字符串转换为 int,19216811 不是您要编码的 int。 192.168.1.1 = 3232235777 作为整数。您可以在解码部分执行与您在解码部分中所做的相反的操作并转换每个八位字节。

【讨论】:

  • 已解决。解码for循环中的byte到int的转换应该是:int.from_bytes([i], 'big')
猜你喜欢
  • 2016-01-19
  • 2020-10-22
  • 2011-08-02
  • 2016-01-19
  • 2013-01-08
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
  • 2011-02-13
相关资源
最近更新 更多