Python socket.error

Python socket.error

我在 aaronbell.com 上找到了这个脚本,我正在尝试使用我的 Dashbutton 连接到 IFTTT。我的 Pi 抛出此错误:

Traceback (most recent call last):
  File "dash.py", line 30, in <module>
    rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
  File "/usr/lib/python2.7/socket.py", line 187, in __init__
    _sock = _realsocket(family, type, proto)
socket.error: [Errno 1] Operation not permitted

这是我的脚本:

import socket
import struct
import binascii
import time
import json
import urllib2

ifttt_key = 'loremipsum'
ifttt_url_button = 'https://maker.ifttt.com/trigger/button_was_pressed/with/key/' + ifttt_key

macs = {
    'AC63BEBA94E1' : 'MiXT4Pi'
}

def trigger_url(url):
    data = '{ "value1" : "' + time.strftime("%Y-%m-%d") + '", "value2" : "' + time.strftime("%H:%M") + '" }'
    req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
    f = urllib2.urlopen(req)
    response = f.read()
    f.close()
    return response

def button_was_pressed():
    print 'triggering button event, response: ' + trigger_url(ifttt_url_button)

rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))

while True:
    packet = rawSocket.recvfrom(2048)
    ethernet_header = packet[0][0:14]
    ethernet_detailed = struct.unpack("!6s6s2s", ethernet_header)
    # skip non-ARP packets
    ethertype = ethernet_detailed[2]
    if ethertype != '\x08\x06':
        continue
    # read out data
    arp_header = packet[0][14:42]
    arp_detailed = struct.unpack("2s2s1s1s2s6s4s6s4s", arp_header)
    source_mac = binascii.hexlify(arp_detailed[5])
    source_ip = socket.inet_ntoa(arp_detailed[6])
    dest_ip = socket.inet_ntoa(arp_detailed[8])
    if source_mac in macs:
        #print "ARP from " + macs[source_mac] + " with IP " + source_ip
        if macs[source_mac] == 'MiXT4Pi':
            button_was_pressed()
    else:
        print "Unknown MAC " + source_mac + " from IP " + source_ip

我尝试将第 30 行更改为:

rawSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.htons(0x0003))

但是出现了类似的错误:

Traceback (most recent call last):
  File "dash.py", line 30, in <module>
    rawSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.htons(0x0003))
  File "/usr/lib/python2.7/socket.py", line 187, in __init__
    _sock = _realsocket(family, type, proto)
socket.error: [Errno 22] Invalid argument

在此先感谢您的帮助!

换行

rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))

至此

rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, 0)

这会奏效。

首先,domain 应该设置为 "AF_INET",就像在结构 sockaddr_in 中一样(上面。)接下来,类型参数告诉内核这是什么类型的套接字:SOCK_STREAM 或 SOCK_DGRAM。最后,只需将协议设置为“0”,让 socket() 根据类型选择正确的协议。 (注意:域比我列出的多得多。类型比我列出的多得多。请参阅 socket() 手册页。此外,还有一种获取协议的 "better" 方法。See the getprotobyname() man page.)