简体   繁体   English

Python 2.7 RAW套接字:ARP标头中的字段缺失和错误

[英]Python 2.7 RAW sockets: missing and wrong fields in ARP header

at the beggining I would like to say that I didn't have any experiences with sockets earlier. 在开始的时候,我想说我以前没有使用套接字的经验。 I am trying to create response ARP packet in python 2.7. 我正在尝试在python 2.7中创建响应ARP数据包。 I have almost done it, but there's a problem: when I was looking at the packet in wireshark i found out that ARP header is missing sender & target mac and sender & target ip fields. 我差不多完成了,但是有一个问题:当我查看Wireshark中的数据包时,我发现ARP标头缺少发件人和目标mac以及发件人和目标ip字段。 Harware size and protocol size fields are wrong as well. Harware大小和协议大小字段也是错误的。 What am I doing wrong? 我究竟做错了什么? Do I pack data wrongly? 我会错误地打包数据吗? Here is source code of the program: 这是程序的源代码:

import socket
import struct
import binascii


def formatMAC(mac):
    return mac.lower().replace(':', '')

def sendPacket(packet):
    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
    s.bind(("wlan0", 0))
    return s.send(packet)

eth_src = formatMAC('A0:88:B4:0A:A5:A8')
eth_dst = formatMAC("18:A6:F7:CF:51:B6")
eth_prt = '0806'

arp_hw_type = '0001'
arp_prt_type = '0800'
arp_hw_size = '0006'
arp_prt_size = "0004"
arp_opcode = '0002'
arp_mac_src = formatMAC('A0:88:B4:0A:A5:A8')
arp_ip_src = '192.168.0.134'
arp_mac_dst = formatMAC('18:A6:F7:CF:51:B6')
arp_ip_dst = '192.168.0.1'

eth_pack = struct.pack("!6s6s2s", binascii.unhexlify(eth_dst), binascii.unhexlify(eth_src), binascii.unhexlify(eth_prt))
arp_pack = struct.pack("2s2s1s1s2s6s4s6s4s",
         binascii.unhexlify(arp_hw_type), 
         binascii.unhexlify(arp_prt_type),
         binascii.unhexlify(arp_hw_size),
         binascii.unhexlify(arp_prt_size),
         binascii.unhexlify(arp_opcode),
         binascii.unhexlify(arp_mac_src),
         socket.inet_aton(arp_ip_src), 
         binascii.unhexlify(arp_mac_dst),
         socket.inet_aton(arp_ip_dst)
         )

packet = eth_pack + arp_pack
print(sendPacket(packet))

Wireshark screenshot Wireshark屏幕截图

Thanks. 谢谢。

If you match up the Wireshark hexdump with what you're trying to send, you'll see that the "hardware address size" and "protocol address size" fields of the actually sent packet are both 00. 如果将Wireshark十六进制转储与您要发送的内容相匹配,您会看到实际发送的数据包的“硬件地址大小”和“协议地址大小”字段均为00。

This is because you passed two bytes to struct.pack (0006 and 0004) but you told it (with 1s ) to only format 1 byte, so it only outputs the first byte. 这是因为您将两个字节传递给struct.pack (0006和0004),但是您告诉它(带有1s )仅格式化了1个字节,因此它仅输出第一个字节。

If you look at the hexdump you'll see that the addresses were actually sent, Wireshark just ignored them because the size was supposed to be 0. 如果您查看十六进制转储,您会看到地址实际上是发送的,Wireshark只是忽略了它们,因为假定大小为0。

Just change 0006 and 0004 to 06 and 04 as these are 1-byte fields. 只需将0006和0004更改为06和04,因为它们是1字节字段。

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

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