使用 python scapy 发送 DHCP Discover

2022-01-19 00:00:00 python network-programming scapy dhcp

问题描述

我是 python 新手,正在学习一些网络编程,我希望通过我的 tap 接口向我的 DHCP 服务器发送一个 DHCP 数据包,并期待它的一些响应.我尝试了几种数据包构建技术,例如结构和 ctypes,最终使用了 scapy.在这里,我能够发送 DHCP 数据包,但无法从 DHCP 服务器获得任何响应(使用 Wireshark 和 tcpdump 分析)..我的数据包看起来与原始 DHCP 数据包相同,但未能得到响应.这是我的代码

I am new to python and learning some network programming, I wish to send an DHCP Packet through my tap interface to my DHCP server and expecting some response from it. I tried with several packet building techniques such a structs and ctypes and ended up with using scapy. Here I am able to send DHCP Packet but unable to get any response from the DHCP server(Analyzed using wireshark and tcpdump)..My packet looked like same as original DHCP packet but failed to get response. Here is my code

import socket
from scapy.all import *

def main():

 if len(sys.argv)<3:
   print " fewer arguments."
   sys.exit(1)
 else:
   tap_interface = sys.argv[1]
   src_mac_address = sys.argv[2]

 ethernet = Ether(dst='ff:ff:ff:ff:ff:ff',src=src_mac_address,type=0x800)
 ip = IP(src ='0.0.0.0',dst='255.255.255.255')
 udp =UDP (sport=68,dport=67)
 fam,hw = get_if_raw_hwaddr(tap_interface)
 bootp = BOOTP(chaddr = hw, ciaddr = '0.0.0.0',xid =  0x01020304,flags= 1)
 dhcp = DHCP(options=[("message-type","discover"),"end"])
 packet = ethernet / ip / udp / bootp / dhcp

 fd = open('/dev/net/tun','r+')
 TUNSETIFF = 0x400454ca
 IFF_TAP = 0x0002
 IFF_NO_PI = 0x1000
 mode = IFF_TAP | IFF_NO_PI
 ifr = struct.pack('16sH', tap_interface, IFF_TAP | IFF_NO_PI)
 fcntl.ioctl(fd,TUNSETIFF,ifr)


 while True:
    sendp(packet, iface = tap_interface)
    time.sleep(10)


 if __name__ == '__main__':
     main()

还有其他方法可以实现吗?如果是这样,请务必提及它们.提前致谢.

Is there any other ways of achieving this? If so please do mention them as well. Thanks in Advance.


解决方案

解决了!我遇到了同样的问题,

Solved ! I had the same problem,

我认为问题出在 srp() 函数上,它无法在端口 68 上接收数据包,但我创建了一个新函数,其中包含一个新线程,用于嗅探 BOOTP 消息并显示数据包字段.你可以模拟它:

sniff(iface=myiface, filter="port 68 and port 67")

sniff(iface=myiface, filter="port 68 and port 67")

然后使用 srp() 或 sendp() func 发送数据包 :)

then send the packet using srp() or sendp() func :)

注意:我使用了多线程机制,因为如果网络上有恶意 DHCP 服务器,我的程序会发送消息和嗅探

NOTE: I have used multithreading mechanism cause my program sends messages and sniffs if a rogue DHCP Server is on the network

相关文章