Python 原始套接字到以太网接口 (Windows) [英] Python Raw Socket to Ethernet Interface (Windows)

查看:31
本文介绍了Python 原始套接字到以太网接口 (Windows)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 DHCP 服务器,第一步是我通过以太网端口发送数据包.我正在尝试将数据包发送到我的以太网接口,但出现错误.

I'm trying to create a DHCP Server and the first step is for me to send packets through my ethernet port. I'm trying to send packets to my Ethernet interface and having an error popping up.

代码如下.

import socket

def sendeth(src, dst, eth_type, payload, interface = "eth0"):
  """Send raw Ethernet packet on interface."""

  assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses
  assert(len(eth_type) == 2) # 16-bit ethernet type

  #s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
  s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)

  # From the docs: "For raw packet
  # sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])"
  s.bind((interface, 0))
  return s.send(src + dst + eth_type + payload)

if __name__ == "__main__":
  print("Sent %d-byte Ethernet packet on eth0" %
    sendeth("\xFE\xED\xFA\xCE\xBE\xEF",
            "\xFE\xED\xFA\xCE\xBE\xEF",
            "\x7A\x05",
            "hello"))

我在创建套接字的方式方面遇到了问题.AF_PACKET 无法识别,所以我假设它仅适用于 Linux.我将其注释掉并在其下方添加了一个新行.我再次运行它,开始出现如下所示的错误.

I was having issues with the way the socket was being created. AF_PACKET is not recognized so I'm assuming that only works for Linux. I commented it out and added a new line below it. I ran it again and I started getting an error shown below.

Traceback (most recent call last):
  File "eth.py", line 27, in <module>
    "hello"))
  File "eth.py", line 19, in sendeth
    s.bind((interface, 0))
  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 11001] getaddrinfo failed

有人知道为什么会这样吗?

Does anyone know why this is happening?

推荐答案

DHCP 是一种 UDP 协议.您不应该需要原始套接字来实现 DHCP 服务器.

DHCP is a UDP protocol. You shouldn't need a raw socket to implement a DHCP server.

使用 AF_INET/SOCK_DGRAM 套接字,并绑定到地址 255.255.255.255 以实现您的服务器.

Use an AF_INET/SOCK_DGRAM socket, and bind to address 255.255.255.255 in order to implement your server.

这篇关于Python 原始套接字到以太网接口 (Windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆