简体   繁体   中英

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). The IP will be of variable length so I don't know if I can use some sort of string character counter.

Any ideas?

Thanks

Regular expressions can be cumbersome. You can also use the split() function

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.

Another way would be to use a library like 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'.' 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.

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.

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
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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