0

I have a text file which have text similar to mentioned below

harry's source ip and port combination is 192.168.4.1/5897 and he is trying to access destination 202.158.14.1/7852

The text may vary. My task is to find the first pair of IP and port.

However my code is not working

import re

with open('traffic.txt', 'r') as file:
    fi = file.readlines()
re_ip = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
re_port = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$\/(\d+)")

for line in fi:
    ip = re.findall(re_ip,line)
    port = re.findall(re_port,line)
    print port , ip
5
  • "my code is not working" - include the complete error message. Commented Sep 8, 2017 at 5:12
  • consider import ipaddress in python 3 Commented Sep 8, 2017 at 5:13
  • 1
    Possible duplicate of Simple Java regex to extract IP address and port from enclosing string. The answer is for Java, but the regex is the same in both languages. Commented Sep 8, 2017 at 5:14
  • 2
    Hint: What hurts you is "^" and "$". Commented Sep 8, 2017 at 5:15
  • Thanks DYZ , without ^ and $ it worked :) Commented Sep 8, 2017 at 5:25

1 Answer 1

2

Correct code

import re

with open('traffic.txt', 'r') as file:
    fi = file.readlines()


re_ip = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
re_port = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/(\d+)")

for line in fi:
    port = re.findall(re_port,line)
    ip = re.findall(re_ip,line)
    print "PORT is  " , port , "ip is " ,ip 
Sign up to request clarification or add additional context in comments.

1 Comment

I feel '/' needs to be replaced with ':' in re_port. re_port = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:(\d+)")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.