无法接收消息 - Python套接字

时间:2015-11-25 18:48:49

标签: python linux sockets ubuntu

我正在尝试使用运行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"

    ... 

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

1 个答案:

答案 0 :(得分:1)

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