Python:在OSX中使用原始套接字 [英] python: using raw socket with OSX

查看:94
本文介绍了Python:在OSX中使用原始套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到了此代码,发现它在OSX上不起作用.没有人知道正确的方法而不使用第三方库吗?

I found this code online and found that it doesn't work on OSX. Does anyone know the correct method without using a third party library?

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对此级别过高,或者至少需要更多的重新编码而不是替换.

apparantly OSX does not have AF_PACKET or PF_PACKET and AF_INET is too high level for this I think, or at the very least requires more recoding than a drop in replacement.

谢谢

推荐答案

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

ok I figured this one out, on a mac I have to use pcap library. Here is the code I came up with.

#!/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中使用原始套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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