4

I'm trying to manipulate the output from tcpdump in python 2.7. What I'm trying to do is remove the port portion of the IP Address.

For example if the input string is

192.168.0.50.XXXX

How would I go about deleting everything after the 4th period so the output would be

192.168.0.50

I've thought about doing something with the length of the string the only thing is port lengths can be anywhere from 1-5 digits in my example(0-9999).

The only thing I can think of is doing something with the # of periods as a normal IP only contains 3 and an IP with Port attached has 4.

Shajal Ahamed
  • 141
  • 2
  • 16
Zac
  • 109
  • 1
  • 1
  • 8

4 Answers4

4

Use rsplit() for the cleanest or most simple route:

s = "192.168.0.50.XXXX"
s = s.rsplit('.',1)[0]

Output:

192.168.0.50

rsplit()

Returns a list of strings after breaking the given string from right side by the specified separator.

l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • 1
    This solution worked for me and seemed to be the most concise solution. Thank you! – Zac Apr 28 '18 at 05:08
2

Try this

print('.'.join("192.168.0.50.XXXX".split('.')[:-1])) #or [:4], depending on what you want. To just remove the port, the -1 should work.
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
2

Split the string into groups using the period as the separator. Take the first four groups and put them together again, using the same period as the separator:

ip = "192.168.0.50.XXXX"
".".join(ip.split(".")[:4])
#'192.168.0.50'
DYZ
  • 55,249
  • 10
  • 64
  • 93
1

I have used split and join function do this.

Here is the step by step process:

ip="192.168.0.50.XXXX"

Split a string and add the data to a string array using a defined separator.

sp=ip.split(".")
#['192', '168', '0', '50', 'XXXX']

To select everything in the array except the last item

sp=sp[:-1]
#['192', '168', '0', '50']

Then join these elements using join function:

".".join(sp)
#'192.168.0.50'
Shajal Ahamed
  • 141
  • 2
  • 16