【閒趣】《轉載》--監控windows主機的網卡信息

原本是想做一個類似於wireshark的流量監控的腳本,後來一想不用做到這個程度(主要是分析數據包麻煩還要再學習),就監控流量流向就可以了,順利的是網上已經有大神把流量流向監控的寫出來了。以下是源代碼:
 

#!/usr/bin/python3
# -*- coding:utf-8 -*-
# 功能:獲取網卡信息

from ctypes import *
import os
import socket
import struct


# IP頭定義
class IP(Structure):
    _fields_ = [
        ("ihl", c_ubyte, 4),
        ("version", c_ubyte, 4),
        ("tos", c_ubyte),
        ("len", c_ushort),
        ("id", c_ushort),
        ("offset", c_ushort),
        ("ttl", c_ubyte),
        ("protocol_num", c_ubyte),
        ("sum", c_ushort),
        ("src", c_ulong),
        ("dst", c_ulong)
    ]

    def __new__(self, socket_buffer=None):
        return self.from_buffer_copy(socket_buffer)

    def __init__(self, socket_buff=None):
        # 協議字段與協議名稱對應
        self.protocol_map = {1: 'ICMP', 2: 'IGMP', 3: 'GGP', 4: 'IP', 6: 'TCP', 17: 'UDP', 41: 'IPV6'}

        # 可讀性更強的ip地址
        self.src_address = socket.inet_ntoa(struct.pack("<L", self.src))
        self.dst_address = socket.inet_ntoa(struct.pack("<L", self.dst))

        # 協議類型
        try:
            self.protocol = self.protocol_map[self.protocol_num]
        except:
            self.protocol = str(self.protocol_num)


if __name__ == "__main__":
    # 監聽主機(獲取本機ip)
    host = '192.168.1.17'
    # 創建原始套接字, 然後綁定在公開接口上
    if os.name == "nt":
        socket_protocol = socket.IPPROTO_IP
    else:
        socket_protocol = socket.IPPROTO_ICMP

    sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
    sniffer.bind((host, 0))

    # 設置在捕獲的數據包中包含的IP頭
    sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

    # 在windows平臺上, 我們需要設置IOCTL以啓用混雜模式
    if os.name == "nt":
        sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
    try:
        while True:
            # 讀取數據包
            raw_buffer = sniffer.recvfrom(65565)[0]

            # 將緩衝區前的20個字段按IP頭進行解析
            ip_header = IP(raw_buffer[0:20])

            # 輸出協議和通信雙方ip地址
            print("Protocol: %s %s -> %s" % (ip_header.protocol, ip_header.src_address, ip_header.dst_address))

    # 出來CTRL-C
    except KeyboardInterrupt:
        # 如果運行在windows上,關閉混雜模式
        if os.name == "nt":
            sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)

運行效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章