[英]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)
Three-four improvements:三四改进:
(?:...)
) instead of capturing groups for parts of the IP address(?:...)
) 而不是捕获 IP 地址部分的组re.findall()
only yields results for captured groups re.findall()
只产生捕获组的结果$
), is this intended?$
) 的末尾,这是有意的吗? If so, the last \\b
is meaningless\\b
是没有意义的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 .
在 regex101.com 上查看工作演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.