转换“ little endian”十六进制字符串到Python中的IP地址 [英] Convert "little endian" hex string to IP address in Python

查看:128
本文介绍了转换“ little endian”十六进制字符串到Python中的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the best way to turn a string in this form into an IP address: "0200A8C0". The "octets" present in the string are in reverse order, i.e. the given example string should generate 192.168.0.2.

推荐答案

套接字模块提供了网络地址处理。

Network address manipulation is provided by the socket module.


socket.inet_ntoa(packed_ip)

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

Convert a 32-bit packed IPv4 address (a string four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary data this function takes as an argument.

您可以使用打包的ip /struct.html#struct.pack rel = noreferrer> struct.pack()
和小端无符号长格式。

You can translate your hex string to packed ip using struct.pack() and the little endian, unsigned long format.

>>> import socket
>>> import struct
>>> addr_long = int("0200A8C0",16)
>>> hex(addr_long)
'0x200a8c0'
>>> struct.pack("<L", addr_long)
'\xc0\xa8\x00\x02'

>>> socket.inet_ntoa(struct.pack("<L", addr_long))
'192.168.0.2'
>>> 

这篇关于转换“ little endian”十六进制字符串到Python中的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆