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
Zoro99
  • 185
  • 3
  • 13
  • "my code is not working" - include the complete error message. – DYZ Sep 08 '17 at 05:12
  • consider `import ipaddress` in python 3 – pylang Sep 08 '17 at 05:13
  • 1
    Possible duplicate of [Simple Java regex to extract IP address and port from enclosing string](https://stackoverflow.com/questions/29757311/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. – DYZ Sep 08 '17 at 05:14
  • 2
    Hint: What hurts you is `"^"` and `"$"`. – DYZ Sep 08 '17 at 05:15
  • Thanks DYZ , without ^ and $ it worked :) – Zoro99 Sep 08 '17 at 05:25

1 Answers1

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 
Zoro99
  • 185
  • 3
  • 13
  • 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+)")` – ajaykools Aug 20 '20 at 19:38