【问题标题】:Can't receive messages - Python sockets无法接收消息 - Python 套接字
【发布时间】:2016-02-28 16:49:09
【问题描述】:

我正在尝试使用运行 Ubuntu 14.04 的计算机上的 python 脚本读取 ARP 请求。 Wireshark 显示我正在接收 ARP 请求,但我无法使用 python 读取它。我不确定问题是否出在我的电脑上,但我认为问题出在我的电脑上,而不是脚本上。

我正在使用sudo python "..../name.py" 运行此脚本

到目前为止,这是我的 python 脚本:

import dpkt
import socket
import binascii
import time

def to_Readble(addr):
    s=list()
    addr=binascii.hexlify(addr)
    for i in xrange(12/2):
        s.append(addr[i*2:i*2+2])
    r=":".join(s)
    return r

def to_Sendable(r):
    s=r.split(":")
    for i in xrange(6):
        s[i]=binascii.unhexlify(s[i])
    addr=''.join(s)
    return addr

def buildARP(src_mac, src_ip, to_mac, to_ip):
    arp_p = dpkt.arp.ARP()
    arp_p.sha = to_Sendable(src_mac) #add configure
    arp_p.spa = socket.inet_aton(src_ip)
    arp_p.tha = to_Sendable(to_mac) #add configure
    arp_p.tpa = socket.inet_aton(to_ip)
    arp_p.op = dpkt.arp.ARP_OP_REPLY #reply

    packet = dpkt.ethernet.Ethernet()
    packet.src = to_Sendable(src_mac)
    packet.dst = to_Sendable(to_mac)
    packet.data = arp_p
    packet.type = dpkt.ethernet.ETH_TYPE_ARP
    return packet


raw_sock=socket.socket(socket.PF_PACKET, socket.SOCK_RAW,socket.htons(0x0003))#changed ver
raw_sock.bind(("eth0", dpkt.ethernet.ETH_TYPE_ARP))
#dns_sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#dns_sock.bind(('',53))
my_mac=to_Readble(raw_sock.getsockname()[-1])
print my_mac
#my_mac="e0:06:e6:d7:c6:c3"
dif="00:00:00:00:00:00"
dif1="ff:ff:ff:ff:ff:ff"
rout="192.168.122.1"
ip_macs={}
print "running"
while 1:
    for i in ip_macs.keys():#sending stuff
        raw_sock.send(str(buildARP(my_mac,rout,ip_macs[i],i)))
    try:
        # raw_sock.recv(1024) Blocks the script!!!!***!!!
        data = raw_sock.recv(1024)
        print "got arp"

    ... 

有人知道我为什么没有收到请求?

【问题讨论】:

  • 我在该代码中没有看到 socket.listen()
  • 为什么我需要倾听?当我输入 raw_sockets.listen(5) 时,脚本崩溃了。

标签: python linux sockets ubuntu


【解决方案1】:

你需要在 socket.bind() 之后使用 socket.listen()。
而不是重复其他答案,请参阅此答案:
(Very) basic Python client socket example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多