y0ko__
y0ko__

Reputation: 11

How do I take IP addresses from packets in python?

ive tried with regex like this, but i just get [] as the output

import socket
import re
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
while True:
    data = str(s.recvfrom(65565))
    pattern = '\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b'
    ips = re.findall(pattern, data)
    print(ips)

Upvotes: 1

Views: 52

Answers (1)

Jan
Jan

Reputation: 43169

Three-four improvements:

  1. Use non-capturing-groups ((?:...)) instead of capturing groups for parts of the IP address
  2. You forgot the raw literal
  3. re.findall() only yields results for captured groups
  4. You want the IP address to be at the end of the string ($), is this intended? If so, the last \b is meaningless

All of these combined, you could possibly use

pattern = r'\b((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.|$)){4})'
#      ---^---

And you should be fine. See a working demo on regex101.com.

Upvotes: 1

Related Questions