利用socket原始套接字实现对以太网头以及IP头的分析

import socket
import sys
import struct
import binascii

class RawSniffer:
    def __init__(self) -> None:       
        try:
            self.raw_s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x800))
            print("[-] Begin to capture packets")

        except Exception as e:
            print("[-] Failed to Start Sniff")
            sys.exit()
    
    def pretty_mac(self,mac_address):
        return "%s:%s:%s:%s:%s:%s"%(mac_address[0:2],mac_address[2:4],mac_address[4:6],mac_address[6:8],mac_address[8:10],mac_address[10:12])

    def run(self):
        while True:
            packet = self.raw_s.recvfrom(2048)

            #Analyze Ethernet header
            raw_ether_header = packet[0][0:14]
            eth_header = struct.unpack('!6s6s2s', raw_ether_header)
            raw_destination_mac = binascii.hexlify(eth_header[0]).decode('utf-8')
            destination_mac = self.pretty_mac(raw_destination_mac)
            raw_source_mac = binascii.hexlify(eth_header[1]).decode('utf-8')
            source_mac = self.pretty_mac(raw_source_mac)
            protocol_type = binascii.hexlify(eth_header[2]).decode('utf-8')

            #Analyze IP header
            ip_header = packet[0][14:34]
            unpack_ip_header = struct.unpack('!12s4s4s', ip_header)
            source_ip = socket.inet_ntoa(unpack_ip_header[1])
            destination_ip = socket.inet_ntoa(unpack_ip_header[2])

            print("""
            Packet info:
                Destination MAC Address: %s
                Source MAC Address:      %s
                Protocl Type:            %s
                Destination IP:          %s
                Source      IP:          %s
            """ % (destination_mac,source_mac, protocol_type, source_ip, destination_ip))
            print("="*100)
    
if __name__ == '__main__':
    rawer = RawSniffer()
    rawer.run()

 

posted @ 2022-06-17 12:07  Jason_huawen  阅读(145)  评论(0编辑  收藏  举报