0

I am trying to parse the results of the TSHARK capture

Here is the line I am filtering on:

Internet Protocol, Src: 10.10.52.250 (10.10.52.250), Dst: 224.0.0.2 (224.0.0.2)

I am trying to extract the Src and Dst,

Here is my code to do that:

str(re.search("Src:\s[0-9\.]{7-15}", a, re.I|re.M).group())[5:]
str(re.search("Dst:\s[0-9\.]{7-15}", a, re.I|re.M).group())[5:]

I keep getting no match when I run this, but when I use the exact length of the IP address in the regular expression it works. ie

str(re.search("Src:\s[0-9\.]{9}", a, re.I|re.M).group())[5:]

Works just fine. How do I fix this problem?

1
  • Do you really want to match "..1234567890123" as a valid IP? Commented Oct 26, 2011 at 20:05

4 Answers 4

3
for match in re.finditer(r"\((\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))\b\)", subject):

This should match any IPV4 IP address. Actual IPs are captured into group 1.

While your regex may work, it is dangerous because 999.999.999.999 is not a valid but it will match.

Sign up to request clarification or add additional context in comments.

2 Comments

I am writing a script that will have to parse traffic during a hacking competition, I need to be able to catch any packets crafted in scapy.They may not be valid IP addresses.
But it's physically impossible to store 999.999.999.999 in an IP packet's address field, which is a 32-bit number. A single 8-bit octet from that field can never represent a decimal number > 255.
3

Looking at the Python regex howto, shouldn't that be {7,15}?

1 Comment

Thanks! That fixed it right away. I'm not quite sure how that worked the last time I tested the script at work.
2

Not very nice:

text = 'fasga@fas#2*^127.0.0.1tfgws5151'

pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
pattern_re = re.compile(pattern)
ip_address = pattern_re.findall(text)

Comments

0

Try using {7,15}:

str(re.search("Src:\s[0-9\.]{7,15}", a, re.I|re.M).group())[5:]
str(re.search("Dst:\s[0-9\.]{7,15}", a, re.I|re.M).group())[5:]

Also, you should check that a group exists first (or put a try/except around it):

groupFound = re.search("Src:\s*[\d\.]{7,15}", a, re.I | re.M)
if groupFound:
    str(groupFound.group())[5:]

# or:

try:
    str(re.search("Src:\s*[\d\.]{7,15}", a, re.I | re.M).group())[5:]
except AttributeError:
    # handle it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.