简体   繁体   English

使用 Python 获取 IP 地址中的最后一个八位字节

[英]Grab the last octet in an IP address using Python

I am writing a Python script that will take an IP address in CIDR format (ie. 1.1.1.0/32 or 10.0.0.1/24) and split the IP into three parts: the first three octets (1.1.1), the last octet (0) and the Subnet mask (32).我正在编写一个 Python 脚本,它将采用 CIDR 格式的 IP 地址(即 1.1.1.0/32 或 10.0.0.1/24)并将 IP 分成三部分:前三个八位字节 (1.1.1),最后一个八位字节 (0) 和子网掩码 (32)。 The IP will be of variable length so I don't know if I can use some sort of string character counter. IP 将是可变长度的,所以我不知道是否可以使用某种字符串字符计数器。

Any ideas?有任何想法吗?

Thanks谢谢

Regular expressions can be cumbersome.正则表达式可能很麻烦。 You can also use the split() function您还可以使用 split() 函数

inp = '192.168.0.1/24'
ip, submask = inp.split('/')
octets = ip.split('.')

Parse the IP into an int, and use bitwise operators to get it.将 IP 解析为 int,并使用按位运算符获取它。

Another way would be to use a library like ipaddr-py .另一种方法是使用像ipaddr-py这样的库。 I'd personally prefer the library.我个人更喜欢图书馆。

Use Regex :使用正则表达式:

#!/usr/bin/python
import re


def extractIP( ipStr):

    l = re.split('(.*)\.(.*)\.(.*)\.(.*)/(.*)', ipStr)
    return l[1:-1]

print extractIP("1.2.3.45/35")

I would use regular expressions.我会使用正则表达式。 You can split all the octets into a list using r'.'您可以使用 r'.' 将所有八位字节拆分为一个列表。 and then recombine them in whatever order you like.然后以您喜欢的任何顺序重新组合它们。 You could write a more complicated re to do it in one stroke, but i think that'd be a bit harder.你可以写一个更复杂的 re 来一次性完成,但我认为那会有点难。

import re
ip = '1.1.1.1/32'
re.split(r'(\.|/)', ip)

Using a regular expression would be simple in this situation.在这种情况下,使用正则表达式会很简单。

(\d{,3}\.\d{,3}\.\d{,3})\.(\d{,3})\/(\d+)

Using the re.match method in conjunction would yield your result.结合使用re.match方法会产生你的结果。

ipstring="192.168.1.1/12"
s=re.split(r"\b(\d{1,3}\.\d{1,3}\.\d{1,3})\.(\d{1,3})\/(\d+)\b",ipstring)
print s
['', '192.168.1', '1', '12', '']
print s[1]
192.168.1
print s[2]
1
print s[3]
12
>>> 

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

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