python:在 OSX 中使用原始套接字

标签 python macos sockets

我在网上找到这段代码,发现它在 OSX 上不起作用。有谁知道不使用第三方库的正确方法吗?

import socket
import struct
import binascii
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)
    arp_header = packet[0][14:42]
    arp_detailed = struct.unpack(“2s2s1s1s2s6s4s6s4s”, arp_header)
    # skip non-ARP packets
    ethertype = ethernet_detailed[2]
    if ethertype != ‘\x08\x06’:
        continue
    source_mac = binascii.hexlify(arp_detailed[5])
    dest_ip = socket.inet_ntoa(arp_detailed[8])
    if source_mac == ‘74c24671971c’:
        print “Tide button pressed!, IP = “ + dest_ip

显然 OSX 没有 AF_PACKET 或 PF_PACKET,我认为 AF_INET 级别太高,或者至少需要更多的重新编码而不是替换掉。

谢谢

最佳答案

好的,我想通了,在 Mac 上我必须使用 pcap 库。这是我想出的代码。

#!/usr/bin/env python2.7

import sys, binascii, subprocess
import dpkt, pcap, socket

cottonelle = 'f0272d8b52c0'

def main():
    name = pcap.lookupdev()
    try:
        pc = pcap.pcap(name)
    except:
        print pc.geterr()

    try:
        print 'listening on %s' % (pc.name)
        for ts, pkt in pc:
            eth = dpkt.ethernet.Ethernet(pkt)
            ip_hdr = eth.data
            if eth.type != dpkt.ethernet.ETH_TYPE_ARP:
                continue
            if binascii.hexlify(eth.src) == cottonelle:
                subprocess.call("/usr/local/bin/stopsim", shell=True)
    except Exception as e:
        print e, pc.geterr()

if __name__ == '__main__':
    main()

关于python:在 OSX 中使用原始套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33447440/

相关文章:

python - 如何将 1 个函数中的字符串输入到另外 2 个函数中,并在 python 中打印它?

python - 替换python 3中的第一个字符串字符

macos - chromakey: ffmpeg 绿色视频去除

MacOS:NSPredicate 查找 "one to one"关系不为零的地方

c - FD_ISSET 是如何工作的?

python - pip 选项 "--force-reinstall"是否重新编译模块? (我正在尝试重新安装cx_Oracle)

python - Pandas:帮助转换数据和编写更好的代码

c++ - 如何检查 lldb 是否可以附加到二进制文件?

python - 客户端未在 Python 中接收数据

c - 如何将字符复制到 srv_address.sin_addr.s_addr