python scapy udp_捕获来自特定客户端UDP(Python)的数据包

I have a question regarding sniffing packets from a specific client. I am running a very simple UDP server as follows:

from socket import *

IPv4 = ""

Port = 54345

ServerSock = socket(AF_INET, SOCK_DGRAM) # UDP

ServerSock.bind((IPv4, Port))

print "Socket is ready to receive data.."

while True:

data, addr = ServerSock.recvfrom(1024) # buffer size is 1024 bytes

print data

and I intend to capture every packet that comes to the port number(54345) and parse its header values. I think it is doable if the packets are saved to .pcap file and probably use scapy to process them but is it possible to process every packet once it arrives using "socket.recvfrom"?. Thanks

解决方案

You've already got the data. However, what you've got is UDP packets and source addresses; if you want the complete raw packet, with the IPv4 and UDP headers, that's different.

On some platforms, you can set a normal UDP socket to IP_HDRINCL, or there are other equivalents. If you do this, each recvfrom will include the headers in the data, so you've already got everything you want.

On other platforms, you can use SOCK_RAW instead of SOCK_DGRAM. What you can do with raw sockets varies dramatically. On many Unix platforms, you can use IPPROTO_UDP with SOCK_RAW, and then bind to a normal UDP address and port, although there may be restrictions, and they're different on each platform. For example, on OS X, you have to be root to create a raw socket, and you can only bind a raw socket to a single-interface address (meaning no ''/INADDR_ANY/'0.0.0.0'). If you Google for "SOCK_RAW Python" and "SOCK_RAW " you should be able to find out what you need. (The last example in the sockets module docs shows how to use raw sockets on Windows.)

Once you've got the data, saving it to a pcap file isn't hard. The format is documented at LibpcapFileFormat at The Wireshark Wiki. If you have any familiarity with the stdlib struct module, it should be easy to figure out how to write this format. Here's a brief sample:

pcap_hdr = struct.pack('=IHHiIII',

0xa1b2c3d4, # magic number

2, 4, # pcap 2.4 format

0, # UTC timezone for timestamps

0, # "in practice, all tools set it to 0"

65535, # max packet length

228) # LINKTYPE_IPV4, or maybe you want LINKTYPE_RAW

pcapfile.write(pcap_hdr)

If you don't want to do that yourself, I don't have any experience with using libraries to write pcap files, but scapy would be the first place I'd look, then the python-libpcap bindings for libpcap/WinPcap. If none of those work, check around PyPI.

If all of this sounds beyond you, you probably don't want to do things this way. Just run your UDP server, and use Wireshark to capture all of the packets sent to it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值