dhcp四个工作步骤
1、客户端通过广播发送dhcp disccover报文寻找服务器端
2、服务器通过单播发送dhcp offer报文向客户提供ip地址等信息
3、客户端通过广播发送dhcp request报文告知服务端本地选择使用哪个ip
4、服务器通过单播发送dhcp ack报文告知客户端ip地址是合法可用的
使用python scapy库模拟dhcp包
dhcp discover包
rom scapy.all import *
import random
def dhcp_offer():
mac=str(randmac()) //随机一个mac
ether_discover=ether(src=mac,dst="ff:ff:ff:ff:ff:ff") //创建ether广播包 目标地址全f
ip_discover=ip(src="0.0.0.0",dst="255.255.255.255") //创建ip广播包 目标全255
udp_discover=udp(dport=67,sport=68) //dhcp使用udp传输 服务端端口67 客户端68
print("随机mac地址为%s" %(mac))
a=mac.replace(":","")
xid_random=random.randint(1,999999999) //dhcp包中xid(请求id)
bootp_discover=bootp(xid=xid_random,chaddr=a) //chaddr=客户端mac
dhcp_discover=dhcp(options=[("message-type","discover"),"end"])
//模拟dhcp包
discover=ether_discover/ip_discover/udp_discover/bootp_discover/dhcp_discover
sendp(discover,iface='以太网',count=1) //发送 iface为发送网卡 count为数量dhcp request包
def dhcp_request():
def j(pkt):
if dhcp in pkt:
if pkt[dhcp].options[0][1]==2: //option为2 说明服务端回复
ether_request = ether(src=pkt[ether].dst, dst="ff:ff:ff:ff:ff:ff")
ip_request = ip(src="0.0.0.0", dst="255.255.255.255")
udp_request = udp(sport=68, dport=67)
bootp_request = bootp(chaddr=pkt[bootp].chaddr, xid=pkt[bootp].xid)
dhcp_request = dhcp(options=[("message-type", 'request'), ("server_id", pkt[dhcp].options[1][1]),
("requested_addr", pkt[bootp].yiaddr), "end"])
request = ether_request / ip_request / udp_request / bootp_request / dhcp_request
sendp(request, iface='以太网',count=1)
print("正在分配ip%s" %(pkt[bootp].yiaddr))
if pkt[dhcp].options[0][1]==5:
print("已经分配ip%s" %(pkt[bootp].yiaddr))
sniff(filter='src port 67', iface='以太网', prn=j,count=5) //监听收到的offer包 prn为处理包的函数
运行效果

此代码只是模拟了客户端,也可用通过scapy模拟服务端
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论