0

I have a file containing a previous tcpdump, so the file has lines in this format:

17:20:03.867998 IP 23.222.75.204.443 > 192.168.0.15.51773: Flags [.], ack 518, win 916, options [nop,nop,TS val 303057114 ecr 43022775], length 0
17:20:03.870231 IP 209.148.192.43.80 > 192.168.0.15.60174: Flags [.], seq 1:1449, ack 511, win 486, options [nop,nop,TS val 1840008838 ecr 43022779], length 1448

My function simply extracts specific strings in each line (the source and destination addresses) and prints them. The strange thing is that it works (everything that should print does) but in the end I get an error.

Here's my code:

def parse_file() :
   try :
      file_object = open("tcp_dump","r") 
      for x in file_object.readlines() :
         source_ip=x.split("IP ")[1].split(" >")[0]
         dest_ip=x.split("> ")[1].split(": Flags")[0]
         print(source_ip)
         print(dest_ip) 
      file_object.close()

   except IOError :
      print("The specified file could not be found/accessed")


parse_file()

Here's the output:

23.222.75.204.443
192.168.0.15.51773
209.148.192.43.80
192.168.0.15.60174
Traceback (most recent call last):
  File "./test", line 26, in <module>
    parse_file()
  File "./test", line 15, in parse_file
    source_ip=x.split("IP ")[1].split(" >")[0]
IndexError: list index out of range
Joshua Dannemann
  • 2,003
  • 1
  • 14
  • 34
DAT BOI
  • 183
  • 1
  • 1
  • 10
  • you probably have an empty line/a line that does have those splits [returns either an empty list or a list with only one item(the original string)]. you already have everything in a try block, add in an `except IndexError:` block to handle it – R Nar Oct 30 '15 at 22:52
  • Or, you can just add an if condition inside for loop to check if the length of the line is greater than 0. If yes, go ahead with your processing, else use continue to go to next iteration. – Harish Talanki Oct 30 '15 at 22:54
  • 2
    apart form the error, personally I'd avoid all that sub-splitting. Just do `y=x.split(); source_ip=y[2]; dest_ip=y[4]` – Pynchia Oct 30 '15 at 22:59
  • `map` and `with` are your friends, use them. The loop can be simplified to `with open('tcpdump.txt','r') as f:` then (indented) `for y in map(lambda x: x.split(), f):` then (indented) `source_ip=y[2]; dest_ip=y[4]; print(source_ip); print(dest_ip)` – Pynchia Oct 30 '15 at 23:07
  • Why not use regex? `import re` and [read the docs](https://docs.python.org/2/library/re.html) – Richard Kenneth Niescior Oct 31 '15 at 00:11

0 Answers0