【发布时间】:2019-06-04 08:25:15
【问题描述】:
我有一个简单的 python 脚本,它创建一个套接字 AF_PACKET,它解析所有 IPv4 数据包并检索源和目标 IP 地址:
import socket
import struct
def get_ip(s):
return '.'.join([str(ord(symbol)) for symbol in s])
def main():
conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
while True:
pkt, addr = conn.recvfrom(65536)
proto = struct.unpack('! H', pkt[12:14])
eth_proto = socket.htons(proto[0])
print('eth_proto = ', eth_proto)
if eth_proto == 8:
src, target = struct.unpack('! 4s 4s', pkt[26:34])
source_ip = get_ip(src)
destination_ip = get_ip(target)
print('Source IP = ', source_ip)
print('Destination IP = ', destination_ip)
main()
是否可以重构获取IP地址,这样看起来会更好,不使用这个循环:
'.'.join([str(ord(symbol)) for symbol in s])
【问题讨论】:
-
请显示
get_ip函数的示例输入和所需的输出。 -
@ruohola 函数 get_ip 的输出是带有 ip 地址的字符串(例如 172.15.75.12),输入是字节数组。也许我可以用不同的方式读取这个字节?
标签: python sockets parsing packet unpack