简体   繁体   English

python中如何使用raw socket收发arp package

[英]How to use raw socket send and receive arp package in python

I need to "send and receive ARP packet in one program".我需要“在一个程序中发送和接收ARP数据包”。 I'm aware that the scapy packet is already do it quiet well, and you just need to pass some argument.我知道scapy包已经很安静了,你只需要传递一些参数。 However, I want to know much further than just pass argument.但是,我想知道的不仅仅是传递参数。 So, if you recommend scapy as answer, it might not help.所以,如果你推荐scapy作为答案,它可能无济于事。

Code代码

python
import struct
import socket
import binascii

rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,
                          socket.htons(0x0003))
rawSocket.bind(("wlp5s0", socket.htons(0x0003)))

source_mac = binascii.unhexlify('00:A0:C9:14:C8:29'.replace(':', ''))
#b'\x00\x00\x00\x00\x00\x00' sender mac address
dest_mac = binascii.unhexlify('ff:ff:ff:ff:ff:ff'.replace(':', ''))
#  b'\xff\xff\xff\xff\xff\xff'  target mac address

source_ip = "192.168.100.3"  # sender ip address
dest_ip = "192.168.100.1"  # target ip address

# Ethernet Header
protocol = 0x0806  # 0x0806 for ARP
eth_hdr = struct.pack("!6s6sH", dest_mac, source_mac, protocol)

# ARP header
htype = 1  # Hardware_type ethernet
ptype = 0x0800  # Protocol type TCP
hlen = 6  # Hardware address Len
plen = 4  # Protocol addr. len
operation = 1  # 1=request/2=reply
src_ip = socket.inet_aton(source_ip)
dst_ip = socket.inet_aton(dest_ip)
arp_hdr = struct.pack("!HHBBH6s4s6s4s", htype, ptype, hlen, plen, operation,
                      source_mac, src_ip, dest_mac, dst_ip)

packet = eth_hdr + arp_hdr
rawSocket.send(packet)
rawSocket.recvfrom(65535)
```
By the way I can clear see the packet already send and reply but `Wireshark` 

截屏

Platform:平台:

OS: Linux Ubuntn 16.04操作系统:Linux Ubuntu 16.04

Interpreter: Python 3.5.2口译员:Python 3.5.2

When you do the bind you should set it to 0 for the second parameter: rawSocket.bind(("wlp5s0", 0))进行绑定时,应将第二个参数设置为 0:rawSocket.bind(("wlp5s0", 0))

I was able to receive ARP packets no problem我能够收到ARP数据包没问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM