Python dhcp 客户端

标签 python udp dhcp

我正在尝试学习如何在多宿主计算机(多个接口(interface))上直接(无库)从 python 发送 DHCP 请求。 我查看了 pydhcplib,但仍然不明白。

此代码在特定接口(interface)(在我的例子中为 eth3 - 未分配 IP)上发送 DHCP 数据包,但它使用 eth0 IP 地址发送。如何将我的源 IP 更改为 0.0.0.0? 在此示例中 dhcp 消息被截断

LOCAL_PORT=68
SERVER_PORT=67
LOCAL_IP="0.0.0.0"
BCAST_IP="255.255.255.255"
LISTEN_DEV="eth3"
MSG_SIZE=2048
Conn=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Conn.settimeout(5)
Conn.setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,LISTEN_DEV+'\0')
Conn.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
Conn.bind((LOCAL_IP, LOCAL_PORT))
# Create DHCP-Discovery
msg="010106003f7d1664......"
Conn.sendto(msg.decode("hex"),(BCAST_IP,SERVER_PORT))
received = Conn.recv(MSG_SIZE)
Conn.close()

最佳答案

我假设您已经了解 Advanced Interprocess Communication Tutorial .

剧透警告:如果您想直接跳到最后一行,请查看 DHCP Query recipe .

编辑:

特殊值 INADDR_ANY(0.0.0.0,或 python 套接字中的空字符串 '')不是 IP 地址。

"When an address is specified as INADDR_ANY (a manifest constant defined in < netinet/in.h >), the system interprets the address as 'any valid address'."

来自 RFC 2131:

In the case of a client using DHCP for initial configuration (before the client's TCP/IP software has been completely configured), DHCP requires creative use of the client's TCP/IP software and liberal interpretation of RFC 1122. The TCP/IP software SHOULD accept and forward to the IP layer any IP packets delivered to the client's hardware address before the IP address is configured; DHCP servers and BOOTP relay agents may not be able to deliver DHCP messages to clients that cannot accept hardware unicast datagrams before the TCP/IP software is configured.

假设您在已配置以太网接口(interface)并具有有效 IP 地址的系统上运行此程序。我不确定为什么您希望源 IP 地址为 0.0.0.0,但也许您可以使用 ifconfig 将接口(interface) IP 设置为 0.0.0.0 以获得您想要的效果。

或者您可以使用 RAW 套接字并自行构建 IP 和 UDP header 以包含任何内容。

关于Python dhcp 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12580544/

相关文章:

python - 如何检查 pymodbus 版本以解码 float_32 值?

python - 如何在Python中仅获取最近2天的文章?

python - reshape Pandas 数据框

c++ - 来自文件的数据 - 发送的字节与 fread() 不匹配

c - 开启环回后如何收到消息?

git - 当两者都在防火墙/NATs/...之后时,如何在 git 存储库之间推送/pull ?

linux - 如何使用 dhclient 将供应商特定选项传递到 DHCP 服务器?

python - 如何将特定的 Pandas 数据框项目合并到一个项目中

bash - 如何使用 Bash 伪造 DHCP 发现数据包?

C# UDP广播和接收示例