简体   繁体   English

如何从python中的数据包中获取IP地址?

[英]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:三四改进:

  1. Use non-capturing-groups ( (?:...) ) instead of capturing groups for parts of the IP address使用非捕获组 ( (?:...) ) 而不是捕获 IP 地址部分的组
  2. You forgot the raw literal你忘记了原始文字
  3. re.findall() only yields results for captured groups re.findall()只产生捕获组的结果
  4. You want the IP address to be at the end of the string ( $ ), is this intended?您希望 IP 地址位于字符串 ( $ ) 的末尾,这是有意的吗? 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.

相关问题 如何在python子列表中填写未使用的IP地址? - How do I fill in unused ip addresses in a python sublist? 如何从Shell脚本的日志文件中获取特定的IP地址并将其转换为Python - How to take specific ip addresses from log file in shell script and convert to Python 如何从python中的snmp解码IP地址 - How to decode ip addresses from snmp in python 如何在python中从网络套接字解压缩LZW数据包? - How do I decompress LZW packets from a network socket in python? Python帮助从文本文件中获取IP地址范围,然后输出该范围内的每个IP地址 - Python help to take in a range of IP addresses from a text file and then output each ip address in the range 我怎样才能增强这个 python 代码来做一个自然排序的 FQN 主机名和 IP 地址列表? - How can I enhance this python code to do a natural sort of a list of FQN hostnames and ip addresses? 在 python 中,如何创建和维护可由一对 IP 地址索引的 IP 地址列表? - In python, how can I create & maintain a list of IP addresses indexable by a pair of IP addresses? Python 3:如何获取将数据包发送到特定IP的NIC? - Python 3: how to get nic from which will be sent packets to certain ip? 在 python 和 selenium 中,如何旋转 IP 地址? - In python with selenium, how do you rotate IP addresses? Python:如何每隔几分钟从Debian服务器上的地址池中更改IP地址? - Python: How can I change ip address every some minute from a pool of addresses on a debian server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM