简体   繁体   English

使用 Python 进行 IP 地址转换

[英]IP address conversion using Python

I want to convert an ip address read from a file in the decimal format (192.168.65.72) to one in binary format {110000001010100001000001010001000}.I am reading the ip address in the decimal format from a file.Find the code snippet below.我想将从十进制格式 (192.168.65.72) 文件中读取的 ip 地址转换为二进制格式 {110000001010100001000001010001000}。我正在从文件中读取十进制格式的 ip 地址。找到下面的代码片段。

/*contains 192.168.65.72*/
filter = open("filter.txt", "r")

for line in filter:
    bytePattern = "([01]?\d\d?|2[0-4]\d|25[0-5])"
    regObj = re.compile("\.".join([bytePattern]*4))
    for match in regObj.finditer(line):
        m1,m2,m3,m4 = match.groups()
        print "%s %s %s %s" %(m1, m2, m3, m4)

I want to convert m1,m2,m3 and m4 each into an 8bit binary value.I cannot figure out a way to do that.I am new to python.Any help will be greatly appreciated.我想将 m1、m2、m3 和 m4 分别转换为 8 位二进制值。我想不出一种方法来做到这一点。我是 python 新手。任何帮助将不胜感激。

Cheers.干杯。

''.join([ bin(int(x))[2:].rjust(8,'0') for x in '123.123.123.123'.split('.')])

Convert an IPv4 address from dotted-quad string format (for example, '123.45.67.89') to 32-bit packed binary format:将 IPv4 地址从点分四元字符串格式(例如,'123.45.67.89')转换为 32 位打包二进制格式:

socket.inet_aton ("192.168.65.72") socket.inet_aton ("192.168.65.72")

If you want a string containing the raw data for the 32 bit IP address:如果您想要一个包含 32 位 IP 地址的原始数据的字符串:

import struct
struct.pack('4B', *(int(x) for x in '123.123.123.123'.split('.')))

Or if you want a 32-bit integer containing the IP address:或者,如果您想要一个包含 IP 地址的 32 位整数:

import struct
struct.unpack('>I', struct.pack('4B', *(int(x) for x in '123.123.123.123'.split('.'))))
>>> bin( 192 )
'0b11000000'

String manipulation does the rest.字符串操作完成剩下的工作。 Note however that in an IP all but the first parts are allowed to be zero.但是请注意,在 IP 中,除了第一部分之外的所有部分都允许为零。

You can use the function clean_ip() from the library DataPrep if you read your file into a DataFrame.如果将文件读入DataFrame,则可以使用库DataPrep 中的函数clean_ip() Install DataPrep with pip install dataprep .使用pip install dataprep

from dataprep.clean import clean_ip
df = pd.DataFrame({"ip": ["192.168.65.72", "123.123.123.123"]})

df2 = clean_ip(df, "ip", output_format="binary")
# print(df2)
                ip                          ip_clean
0    192.168.65.72  11000000101010000100000101001000
1  123.123.123.123  01111011011110110111101101111011

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

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