Python Forum

Full Version: python code wanted: grep IP address
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
actually, this would be better as a function. given a string, find the first valid IPv4 or IPv6 address in the string, returning a 2-tuple of the slice of the string the address is at.

find_ip_address('foo8.8.4.4bar') -> (3,10)

find_ip_address('myIPaddress') -> None
that could be a useful enough start if it also did ipv6.
How about this: https://gist.github.com/mnordhoff/2213179
I didn't spend much time looking at it, so may or may not be useful
holy **** !!!! those are very complex expressions. i think i will avoid those for now. i would have no chance dealing with any bugs. i am still a noob at REs of any basis.

my brain already hurts just looking at that.
There's a ipaddress library that would validated correct for both IPv4/IPv6.
So i would think of just to use regex to get IPv4/IPv6 address whole of out text,then use ipaddress for validation.
Example.
>>> import re
>>> import ipaddress
>>> 
>>> s = 'foo8.8.4.4bar'
>>> ip = re.search(r'(\d.*\d)', s).group(1)
>>> ip
'8.8.4.4'
>>> ipaddress.ip_address(ip)
IPv4Address('8.8.4.4')

# Not valid 
>>> s = 'foo8.256.4.4bar'
>>> ip = re.search(r'(\d.*\d)', s).group(1)
>>> ipaddress.ip_address(ip)
Traceback (most recent call last):
  File "<string>", line 449, in runcode
  File "<interactive input>", line 1, in <module>
  File "C:\python37\lib\ipaddress.py", line 54, in ip_address
    address)
ValueError: '8.256.4.4' does not appear to be an IPv4 or IPv6 address
(Jul-08-2018, 02:10 AM)Larz60+ Wrote: [ -> ]How about this: https://gist.github.com/mnordhoff/2213179
I didn't spend much time looking at it, so may or may not be useful

This didn't worked for me. I will be kind if I will be given more tips. Cheers to any input.
one idea is to step through the string and run a validate at each position until a positive result. then the next issue is the length or end position. but if the use case is to know whether or not the string has and address, such as doing a grep for an ip address, this would be enough.

one way to check for length after the starting position is found is to increment the length as the validation test is done and use the previous value when a failure is hit if the longest address is wanted. if the shortest is wanted, such as 1.1.1.1 when 1.1.1.123 is there, just return at the first positive.

validation could be done by socket.inet_pton() with the appropriate address family flags.