Alopex
Alopex

Reputation: 141

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

I need to "send and receive ARP packet in one program". I'm aware that the scapy packet is already do it quiet well, and you just need to pass some argument. However, I want to know much further than just pass argument. So, if you recommend scapy as answer, it might not help.

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` 

Screenshot

Platform:

OS: Linux Ubuntn 16.04

Interpreter: Python 3.5.2

Upvotes: 1

Views: 2792

Answers (1)

sdog
sdog

Reputation: 1

When you do the bind you should set it to 0 for the second parameter: rawSocket.bind(("wlp5s0", 0))

I was able to receive ARP packets no problem

Upvotes: 0

Related Questions