简体   繁体   English

Python:在IP地址八位字节之间执行数学功能

[英]Python: Performing Mathematical Functions between IP Address Octets

I'm trying to perform the following: 我正在尝试执行以下操作:

firstoctet * 256 + secondoctet = * 256 + thirdoctet = * 256 + fourthoctet = x

When I use this as an example : 当我以这个为例:

64.233.187.99 (google.com)
64 * 256 + 233 = * 256 + 187 = * 256 + 99 = http://1089059683/

Can someone please provide a method as to how this can be done? 有人可以提供一种方法来做到这一点吗? The mathematical sequence is no problem, i'm just unsure as to how I can take the octet values out of the decimal points to perform the math functions. 数学顺序没问题,我不确定如何从小数点后取八位位组值来执行数学功能。

Thanks in advance! 提前致谢!

If you're on Python 3.3 or higher, you can leverage the ipaddress module to avoid reinventing the wheel, and it even provides a useful view as bytes that int.from_bytes can efficiently convert to a real int : 如果您使用的是Python 3.3或更高版本,则可以利用ipaddress模块来避免重新发明轮子,它甚至还提供了一个有用的视图,因为int.from_bytes bytes可以有效地转换为真正的int

from ipaddress import IPv4Address

ip_as_addr = IPv4Address("64.233.187.99")
ip_as_int = int.from_bytes(ip_as_addr.packed, 'big')
print(ip_as_int, hex(ip_as_int))

gets you output of 1089059683 0x40e9bb63 . 获取1089059683 0x40e9bb63输出。

You could do this by hand if you really wanted to, I just like the self-documenting aspect of the above code. 如果您确实愿意,可以手动执行此操作,就像上述代码的自记录方面一样。 If Py 3.3+ isn't an option, you can get the same results with: 如果不选择Py 3.3+,则可以通过以下方式获得相同的结果:

octets = map(int, "64.233.187.99".split('.'))
ip_as_int = sum(octet << ((3 - i) * 8) for i, octet in enumerate(octets))

That just splits the octets apart, converts them to int , then shifts each of them left by 24, 16, 8 and 0 bits (to align the octets properly), which then allows sum to combine them into a single int . 只需将八位字节分开,将它们转换为int ,然后将它们分别左移24、16、8和0位(以正确对齐八位字节),然后允许sum将它们组合成单个int

Convert an IP address string to a list of integers like this: 将IP地址字符串转换为整数列表,如下所示:

ip_as_string = "64.233.187.99"
ip_as_ints = [int(a) for a in ip_as_string.split('.')]

ip_as_ints will be [64, 233, 187, 99]. ip_as_ints为[ ip_as_ints ]。

I will guess that the mathematical expression that you intend to perform is RPN for converting the byte sequence from a base-256 representation to a single number. 我猜想您打算执行的数学表达式是RPN,用于将字节序列从base-256表示形式转换为单个数字。 (Thanks to ShadowRanger for showing this). (感谢ShadowRanger展示了这一点)。 You can obtain that single number easily as follows: 您可以很容易地获得该单号,如下所示:

x = functools.reduce(lambda x,y: (x << 8) | y, ip_as_ints, 0)
print(x)

x is 1089059683. x是1089059683。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM