<repo_name>futureer/QSniffer<file_sep>/Ui_QSniffer.py
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file '/Users/qinchenchong/workspace/QSniffer/QSniffer.ui'
#
# Created: Tue Oct 23 01:24:35 2012
#      by: PyQt4 UI code generator 4.9.5
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(960, 687)
        self.centralWidget = QtGui.QWidget(MainWindow)
        self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
        self.pktGroupBox = QtGui.QGroupBox(self.centralWidget)
        self.pktGroupBox.setGeometry(QtCore.QRect(250, 73, 701, 600))
        self.pktGroupBox.setObjectName(_fromUtf8("pktGroupBox"))
        self.pktTableWidget = QtGui.QTableWidget(self.pktGroupBox)
        self.pktTableWidget.setGeometry(QtCore.QRect(10, 31, 680, 330))
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pktTableWidget.sizePolicy().hasHeightForWidth())
        self.pktTableWidget.setSizePolicy(sizePolicy)
        self.pktTableWidget.setRowCount(0)
        self.pktTableWidget.setObjectName(_fromUtf8("pktTableWidget"))
        self.pktTableWidget.setColumnCount(7)
        item = QtGui.QTableWidgetItem()
        self.pktTableWidget.setHorizontalHeaderItem(0, item)
        item = QtGui.QTableWidgetItem()
        self.pktTableWidget.setHorizontalHeaderItem(1, item)
        item = QtGui.QTableWidgetItem()
        self.pktTableWidget.setHorizontalHeaderItem(2, item)
        item = QtGui.QTableWidgetItem()
        self.pktTableWidget.setHorizontalHeaderItem(3, item)
        item = QtGui.QTableWidgetItem()
        self.pktTableWidget.setHorizontalHeaderItem(4, item)
        item = QtGui.QTableWidgetItem()
        self.pktTableWidget.setHorizontalHeaderItem(5, item)
        item = QtGui.QTableWidgetItem()
        self.pktTableWidget.setHorizontalHeaderItem(6, item)
        self.pktTableWidget.horizontalHeader().setVisible(True)
        self.pktTableWidget.horizontalHeader().setCascadingSectionResizes(False)
        self.pktTableWidget.verticalHeader().setVisible(False)
        self.pktTreeWidget = QtGui.QTreeWidget(self.pktGroupBox)
        self.pktTreeWidget.setGeometry(QtCore.QRect(10, 370, 340, 221))
        self.pktTreeWidget.setObjectName(_fromUtf8("pktTreeWidget"))
        self.pktTreeWidget.headerItem().setText(0, _fromUtf8("1"))
        self.pkt0xBrowser = QtGui.QTextBrowser(self.pktGroupBox)
        self.pkt0xBrowser.setGeometry(QtCore.QRect(360, 370, 190, 221))
        self.pkt0xBrowser.setObjectName(_fromUtf8("pkt0xBrowser"))
        self.pktAsciiBrowser = QtGui.QTextBrowser(self.pktGroupBox)
        self.pktAsciiBrowser.setGeometry(QtCore.QRect(559, 370, 131, 220))
        self.pktAsciiBrowser.setObjectName(_fromUtf8("pktAsciiBrowser"))
        self.filterGroupBox = QtGui.QGroupBox(self.centralWidget)
        self.filterGroupBox.setGeometry(QtCore.QRect(250, 11, 701, 61))
        self.filterGroupBox.setObjectName(_fromUtf8("filterGroupBox"))
        self.filterLineEdit = QtGui.QLineEdit(self.filterGroupBox)
        self.filterLineEdit.setGeometry(QtCore.QRect(20, 30, 281, 22))
        self.filterLineEdit.setObjectName(_fromUtf8("filterLineEdit"))
        self.filterApplyButton = QtGui.QPushButton(self.filterGroupBox)
        self.filterApplyButton.setGeometry(QtCore.QRect(310, 26, 101, 32))
        self.filterApplyButton.setObjectName(_fromUtf8("filterApplyButton"))
        self.filterClearButton = QtGui.QPushButton(self.filterGroupBox)
        self.filterClearButton.setGeometry(QtCore.QRect(410, 26, 101, 32))
        self.filterClearButton.setObjectName(_fromUtf8("filterClearButton"))
        self.filterMsgLable = QtGui.QLabel(self.filterGroupBox)
        self.filterMsgLable.setGeometry(QtCore.QRect(520, 32, 141, 16))
        self.filterMsgLable.setText(_fromUtf8(""))
        self.filterMsgLable.setObjectName(_fromUtf8("filterMsgLable"))
        self.devGroupBox = QtGui.QGroupBox(self.centralWidget)
        self.devGroupBox.setGeometry(QtCore.QRect(10, 10, 231, 71))
        self.devGroupBox.setObjectName(_fromUtf8("devGroupBox"))
        self.devLabel = QtGui.QLabel(self.devGroupBox)
        self.devLabel.setGeometry(QtCore.QRect(10, 35, 51, 20))
        self.devLabel.setObjectName(_fromUtf8("devLabel"))
        self.devComboBox = QtGui.QComboBox(self.devGroupBox)
        self.devComboBox.setGeometry(QtCore.QRect(60, 32, 161, 26))
        self.devComboBox.setObjectName(_fromUtf8("devComboBox"))
        self.optGroupBox = QtGui.QGroupBox(self.centralWidget)
        self.optGroupBox.setGeometry(QtCore.QRect(10, 90, 231, 101))
        self.optGroupBox.setObjectName(_fromUtf8("optGroupBox"))
        self.promisCheckBox = QtGui.QCheckBox(self.optGroupBox)
        self.promisCheckBox.setGeometry(QtCore.QRect(20, 30, 151, 20))
        self.promisCheckBox.setObjectName(_fromUtf8("promisCheckBox"))
        self.stopButton = QtGui.QPushButton(self.optGroupBox)
        self.stopButton.setGeometry(QtCore.QRect(80, 60, 61, 32))
        self.stopButton.setObjectName(_fromUtf8("stopButton"))
        self.startButton = QtGui.QPushButton(self.optGroupBox)
        self.startButton.setGeometry(QtCore.QRect(10, 60, 61, 32))
        self.startButton.setObjectName(_fromUtf8("startButton"))
        self.clearButton = QtGui.QPushButton(self.optGroupBox)
        self.clearButton.setGeometry(QtCore.QRect(150, 60, 71, 32))
        self.clearButton.setObjectName(_fromUtf8("clearButton"))
        self.statGroupBox = QtGui.QGroupBox(self.centralWidget)
        self.statGroupBox.setGeometry(QtCore.QRect(10, 300, 231, 321))
        self.statGroupBox.setObjectName(_fromUtf8("statGroupBox"))
        self.totalLabel = QtGui.QLabel(self.statGroupBox)
        self.totalLabel.setGeometry(QtCore.QRect(10, 27, 41, 16))
        self.totalLabel.setObjectName(_fromUtf8("totalLabel"))
        self.totalCountLabel = QtGui.QLabel(self.statGroupBox)
        self.totalCountLabel.setGeometry(QtCore.QRect(70, 26, 61, 20))
        self.totalCountLabel.setText(_fromUtf8(""))
        self.totalCountLabel.setObjectName(_fromUtf8("totalCountLabel"))
        self.ethernetLabel = QtGui.QLabel(self.statGroupBox)
        self.ethernetLabel.setGeometry(QtCore.QRect(10, 50, 62, 16))
        self.ethernetLabel.setObjectName(_fromUtf8("ethernetLabel"))
        self.arpLabel = QtGui.QLabel(self.statGroupBox)
        self.arpLabel.setGeometry(QtCore.QRect(30, 70, 31, 16))
        self.arpLabel.setObjectName(_fromUtf8("arpLabel"))
        self.arpCountLabel = QtGui.QLabel(self.statGroupBox)
        self.arpCountLabel.setGeometry(QtCore.QRect(70, 70, 62, 16))
        self.arpCountLabel.setText(_fromUtf8(""))
        self.arpCountLabel.setObjectName(_fromUtf8("arpCountLabel"))
        self.rarpCountLabel = QtGui.QLabel(self.statGroupBox)
        self.rarpCountLabel.setGeometry(QtCore.QRect(80, 90, 62, 16))
        self.rarpCountLabel.setText(_fromUtf8(""))
        self.rarpCountLabel.setObjectName(_fromUtf8("rarpCountLabel"))
        self.rarpLabel = QtGui.QLabel(self.statGroupBox)
        self.rarpLabel.setGeometry(QtCore.QRect(30, 90, 41, 16))
        self.rarpLabel.setObjectName(_fromUtf8("rarpLabel"))
        self.ipLabel_2 = QtGui.QLabel(self.statGroupBox)
        self.ipLabel_2.setGeometry(QtCore.QRect(30, 110, 21, 16))
        self.ipLabel_2.setObjectName(_fromUtf8("ipLabel_2"))
        self.ipCountLabel = QtGui.QLabel(self.statGroupBox)
        self.ipCountLabel.setGeometry(QtCore.QRect(60, 110, 62, 16))
        self.ipCountLabel.setText(_fromUtf8(""))
        self.ipCountLabel.setObjectName(_fromUtf8("ipCountLabel"))
        self.ipv6Label_2 = QtGui.QLabel(self.statGroupBox)
        self.ipv6Label_2.setGeometry(QtCore.QRect(30, 130, 35, 16))
        self.ipv6Label_2.setObjectName(_fromUtf8("ipv6Label_2"))
        self.ipv6CountLabel = QtGui.QLabel(self.statGroupBox)
        self.ipv6CountLabel.setGeometry(QtCore.QRect(70, 130, 62, 16))
        self.ipv6CountLabel.setText(_fromUtf8(""))
        self.ipv6CountLabel.setObjectName(_fromUtf8("ipv6CountLabel"))
        self.internetLabel = QtGui.QLabel(self.statGroupBox)
        self.internetLabel.setGeometry(QtCore.QRect(10, 150, 62, 16))
        self.internetLabel.setObjectName(_fromUtf8("internetLabel"))
        self.tcpLabel = QtGui.QLabel(self.statGroupBox)
        self.tcpLabel.setGeometry(QtCore.QRect(30, 170, 31, 16))
        self.tcpLabel.setObjectName(_fromUtf8("tcpLabel"))
        self.tcpCountLabel = QtGui.QLabel(self.statGroupBox)
        self.tcpCountLabel.setGeometry(QtCore.QRect(70, 170, 62, 16))
        self.tcpCountLabel.setText(_fromUtf8(""))
        self.tcpCountLabel.setObjectName(_fromUtf8("tcpCountLabel"))
        self.udpLabel = QtGui.QLabel(self.statGroupBox)
        self.udpLabel.setGeometry(QtCore.QRect(30, 190, 33, 16))
        self.udpLabel.setObjectName(_fromUtf8("udpLabel"))
        self.udpCountLabel = QtGui.QLabel(self.statGroupBox)
        self.udpCountLabel.setGeometry(QtCore.QRect(70, 190, 62, 16))
        self.udpCountLabel.setText(_fromUtf8(""))
        self.udpCountLabel.setObjectName(_fromUtf8("udpCountLabel"))
        self.icmpLabel = QtGui.QLabel(self.statGroupBox)
        self.icmpLabel.setGeometry(QtCore.QRect(30, 210, 41, 16))
        self.icmpLabel.setObjectName(_fromUtf8("icmpLabel"))
        self.icmpCountLabel = QtGui.QLabel(self.statGroupBox)
        self.icmpCountLabel.setGeometry(QtCore.QRect(80, 210, 62, 16))
        self.icmpCountLabel.setText(_fromUtf8(""))
        self.icmpCountLabel.setObjectName(_fromUtf8("icmpCountLabel"))
        self.igmpCountLabel = QtGui.QLabel(self.statGroupBox)
        self.igmpCountLabel.setGeometry(QtCore.QRect(80, 230, 62, 16))
        self.igmpCountLabel.setText(_fromUtf8(""))
        self.igmpCountLabel.setObjectName(_fromUtf8("igmpCountLabel"))
        self.igmpLabel = QtGui.QLabel(self.statGroupBox)
        self.igmpLabel.setGeometry(QtCore.QRect(30, 230, 41, 16))
        self.igmpLabel.setObjectName(_fromUtf8("igmpLabel"))
        self.othersLabel = QtGui.QLabel(self.statGroupBox)
        self.othersLabel.setGeometry(QtCore.QRect(10, 270, 51, 16))
        self.othersLabel.setObjectName(_fromUtf8("othersLabel"))
        self.othersCountLabel = QtGui.QLabel(self.statGroupBox)
        self.othersCountLabel.setGeometry(QtCore.QRect(70, 270, 61, 20))
        self.othersCountLabel.setText(_fromUtf8(""))
        self.othersCountLabel.setObjectName(_fromUtf8("othersCountLabel"))
        self.icmpv6Label = QtGui.QLabel(self.statGroupBox)
        self.icmpv6Label.setGeometry(QtCore.QRect(30, 250, 51, 16))
        self.icmpv6Label.setObjectName(_fromUtf8("icmpv6Label"))
        self.icmpv6CountLabel = QtGui.QLabel(self.statGroupBox)
        self.icmpv6CountLabel.setGeometry(QtCore.QRect(90, 250, 62, 16))
        self.icmpv6CountLabel.setText(_fromUtf8(""))
        self.icmpv6CountLabel.setObjectName(_fromUtf8("icmpv6CountLabel"))
        self.errorCountLabel = QtGui.QLabel(self.statGroupBox)
        self.errorCountLabel.setGeometry(QtCore.QRect(60, 290, 61, 20))
        self.errorCountLabel.setText(_fromUtf8(""))
        self.errorCountLabel.setObjectName(_fromUtf8("errorCountLabel"))
        self.errorLabel = QtGui.QLabel(self.statGroupBox)
        self.errorLabel.setGeometry(QtCore.QRect(10, 290, 51, 16))
        self.errorLabel.setObjectName(_fromUtf8("errorLabel"))
        self.dumpGroupBox = QtGui.QGroupBox(self.centralWidget)
        self.dumpGroupBox.setGeometry(QtCore.QRect(10, 200, 231, 91))
        self.dumpGroupBox.setObjectName(_fromUtf8("dumpGroupBox"))
        self.importButton = QtGui.QPushButton(self.dumpGroupBox)
        self.importButton.setGeometry(QtCore.QRect(20, 27, 90, 32))
        self.importButton.setObjectName(_fromUtf8("importButton"))
        self.exportButton = QtGui.QPushButton(self.dumpGroupBox)
        self.exportButton.setGeometry(QtCore.QRect(120, 27, 90, 32))
        self.exportButton.setObjectName(_fromUtf8("exportButton"))
        self.dumpLabel = QtGui.QLabel(self.dumpGroupBox)
        self.dumpLabel.setGeometry(QtCore.QRect(10, 60, 210, 16))
        self.dumpLabel.setText(_fromUtf8(""))
        self.dumpLabel.setObjectName(_fromUtf8("dumpLabel"))
        MainWindow.setCentralWidget(self.centralWidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "QSniffer", None, QtGui.QApplication.UnicodeUTF8))
        self.pktGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Packets", None, QtGui.QApplication.UnicodeUTF8))
        item = self.pktTableWidget.horizontalHeaderItem(0)
        item.setText(QtGui.QApplication.translate("MainWindow", "No", None, QtGui.QApplication.UnicodeUTF8))
        item = self.pktTableWidget.horizontalHeaderItem(1)
        item.setText(QtGui.QApplication.translate("MainWindow", "Info", None, QtGui.QApplication.UnicodeUTF8))
        item = self.pktTableWidget.horizontalHeaderItem(2)
        item.setText(QtGui.QApplication.translate("MainWindow", "Source", None, QtGui.QApplication.UnicodeUTF8))
        item = self.pktTableWidget.horizontalHeaderItem(3)
        item.setText(QtGui.QApplication.translate("MainWindow", "Destination", None, QtGui.QApplication.UnicodeUTF8))
        item = self.pktTableWidget.horizontalHeaderItem(4)
        item.setText(QtGui.QApplication.translate("MainWindow", "Protocol", None, QtGui.QApplication.UnicodeUTF8))
        item = self.pktTableWidget.horizontalHeaderItem(5)
        item.setText(QtGui.QApplication.translate("MainWindow", "Length", None, QtGui.QApplication.UnicodeUTF8))
        item = self.pktTableWidget.horizontalHeaderItem(6)
        item.setText(QtGui.QApplication.translate("MainWindow", "Info", None, QtGui.QApplication.UnicodeUTF8))
        self.filterGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Filter", None, QtGui.QApplication.UnicodeUTF8))
        self.filterApplyButton.setText(QtGui.QApplication.translate("MainWindow", "Apply", None, QtGui.QApplication.UnicodeUTF8))
        self.filterClearButton.setText(QtGui.QApplication.translate("MainWindow", "Clear", None, QtGui.QApplication.UnicodeUTF8))
        self.devGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Interface", None, QtGui.QApplication.UnicodeUTF8))
        self.devLabel.setText(QtGui.QApplication.translate("MainWindow", "Device:", None, QtGui.QApplication.UnicodeUTF8))
        self.optGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Options", None, QtGui.QApplication.UnicodeUTF8))
        self.promisCheckBox.setText(QtGui.QApplication.translate("MainWindow", "Promiscuous Mode", None, QtGui.QApplication.UnicodeUTF8))
        self.stopButton.setText(QtGui.QApplication.translate("MainWindow", "Stop", None, QtGui.QApplication.UnicodeUTF8))
        self.startButton.setText(QtGui.QApplication.translate("MainWindow", "Start", None, QtGui.QApplication.UnicodeUTF8))
        self.clearButton.setText(QtGui.QApplication.translate("MainWindow", "Clear", None, QtGui.QApplication.UnicodeUTF8))
        self.statGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Statistics", None, QtGui.QApplication.UnicodeUTF8))
        self.totalLabel.setText(QtGui.QApplication.translate("MainWindow", "Total: ", None, QtGui.QApplication.UnicodeUTF8))
        self.ethernetLabel.setText(QtGui.QApplication.translate("MainWindow", "Ethernet:", None, QtGui.QApplication.UnicodeUTF8))
        self.arpLabel.setText(QtGui.QApplication.translate("MainWindow", "ARP: ", None, QtGui.QApplication.UnicodeUTF8))
        self.rarpLabel.setText(QtGui.QApplication.translate("MainWindow", "RARP: ", None, QtGui.QApplication.UnicodeUTF8))
        self.ipLabel_2.setText(QtGui.QApplication.translate("MainWindow", "IP: ", None, QtGui.QApplication.UnicodeUTF8))
        self.ipv6Label_2.setText(QtGui.QApplication.translate("MainWindow", "IPv6: ", None, QtGui.QApplication.UnicodeUTF8))
        self.internetLabel.setText(QtGui.QApplication.translate("MainWindow", "Internet:", None, QtGui.QApplication.UnicodeUTF8))
        self.tcpLabel.setText(QtGui.QApplication.translate("MainWindow", "TCP: ", None, QtGui.QApplication.UnicodeUTF8))
        self.udpLabel.setText(QtGui.QApplication.translate("MainWindow", "UDP: ", None, QtGui.QApplication.UnicodeUTF8))
        self.icmpLabel.setText(QtGui.QApplication.translate("MainWindow", "ICMP: ", None, QtGui.QApplication.UnicodeUTF8))
        self.igmpLabel.setText(QtGui.QApplication.translate("MainWindow", "IGMP: ", None, QtGui.QApplication.UnicodeUTF8))
        self.othersLabel.setText(QtGui.QApplication.translate("MainWindow", "Others: ", None, QtGui.QApplication.UnicodeUTF8))
        self.icmpv6Label.setText(QtGui.QApplication.translate("MainWindow", "ICMPv6: ", None, QtGui.QApplication.UnicodeUTF8))
        self.errorLabel.setText(QtGui.QApplication.translate("MainWindow", "Error: ", None, QtGui.QApplication.UnicodeUTF8))
        self.dumpGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Dump", None, QtGui.QApplication.UnicodeUTF8))
        self.importButton.setText(QtGui.QApplication.translate("MainWindow", "Import...", None, QtGui.QApplication.UnicodeUTF8))
        self.exportButton.setText(QtGui.QApplication.translate("MainWindow", "Export...", None, QtGui.QApplication.UnicodeUTF8))


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

<file_sep>/Analyzer.py
from winpcapy import pcap_pkthdr
import time, inspect, dpkt
from PyQt4 import QtGui, QtCore
from Util import Statistics, PktItem, NetFormat

class Analyer():
    def __init__(self, pktList, table, window):
        self.statistics = Statistics()
        self.pktList = pktList
        self.table = table  #tablewidget
        self.window = window
        self.itemlist = []
        self.goon = False
        
    def start_analize(self):
        self.goon = True
        while self.goon:
            if len(self.pktList.pktlist) > 0:
                self.pktList.mutex.acquire()
                p = self.pktList.pktlist.pop(0)
                self.pktList.mutex.release()
                
                item = self.analize(p)
                self.itemlist.append(item)
                self.show_item(item)
            else:
                time.sleep(0.01)
            self.statistics.updateStatistics(self.window)
    def stop_analize(self):
        self.goon = False
    def clear(self):
        self.statistics = Statistics()
        self.statistics.updateStatistics(self.window)
        del self.itemlist[:]
    
    def analize(self, pkt):
        header, data = pkt
        pktItem = PktItem()
        pktItem.rawpkt = pkt
        frame = dpkt.ethernet.Ethernet(data)
        
        self.handle_frame(pktItem, header, frame)
        
        if frame.type == dpkt.ethernet.ETH_TYPE_ARP:
            self.handle_arp(pktItem, frame.data)
        elif frame.type == dpkt.ethernet.ETH_TYPE_IP:
            self.handle_ip(pktItem, frame.data)
        elif frame.type == dpkt.ethernet.ETH_TYPE_IP6:
            self.handle_ipv6(pktItem, frame.data)
        else:
            self.handle_unknown(pktItem, frame.data)
            print '0x%.4x'%frame.type
        return pktItem
        
    def handle_frame(self, pktItem, header, frame):
        """
        assume that no error occur in the header section
        """
        local_tv_sec = header.ts.tv_sec
        ltime = time.localtime(local_tv_sec);
        pktItem.time = time.strftime("%H:%M:%S", ltime) # time
        
        pktItem.len = header.len    # length
        
        pktItem.protocol = 'Ethernet'   # protocol
        pktItem.src_mac = NetFormat.ntoa_mac(frame.src)  # src_mac
        pktItem.dst_mac = NetFormat.ntoa_mac(frame.dst)  # dst_mac
        
        self.statistics.total += 1
    
    def handle_arp(self, pktItem, data):
        if data.op == dpkt.arp.ARP_OP_REQUEST:
            pktItem.protocol = 'ARP'
            self.statistics.arp += 1
        elif data.op == dpkt.arp.ARP_OP_REPLY:
            pktItem.protocol = 'ARP'
            self.statistics.arp += 1
        elif data.op == dpkt.arp.ARP_OP_REVREQUEST:
            pktItem.protocol = 'RARP'
            self.statistics.rarp += 1
        elif data.op == dpkt.arp.ARP_OP_REVREPLY:
            pktItem.protocol = 'RARP'
            self.statistics.rarp += 1
        else:
            self.handle_error(pktItem)
    
    def handle_ip(self, pktItem, data):
        pktItem.src_ip = NetFormat.ntoa_ip(data.src)
        pktItem.dst_ip = NetFormat.ntoa_ip(data.dst)
        pktItem.protocol = 'IP'
        self.statistics.ip += 1
        if data.p == dpkt.ip.IP_PROTO_TCP:
            self.handle_tcp(pktItem, data.data)
        elif data.p == dpkt.ip.IP_PROTO_UDP:
            self.handle_udp(pktItem, data.data)
        elif data.p == dpkt.ip.IP_PROTO_ICMP:
            self.handle_icmp(pktItem, data.data)
        elif data.p == dpkt.ip.IP_PROTO_IGMP:
            self.handle_igmp(pktItem, data.data)
        else:
            self.handle_unknown(pktItem, data.data)
    
    def handle_ipv6(self, pktItem, data):
        pktItem.src_ip = NetFormat.ntoa_ipv6(data.src)
        pktItem.dst_ip = NetFormat.ntoa_ipv6(data.dst)
        pktItem.protocol = 'IPv6'
        self.statistics.ipv6 += 1
        if data.p == dpkt.ip.IP_PROTO_TCP:
            self.handle_tcp(pktItem, data.data)
        elif data.p == dpkt.ip.IP_PROTO_UDP:
            self.handle_udp(pktItem, data.data)
        elif data.p == dpkt.ip.IP_PROTO_ICMP6:
            self.handle_icmp(pktItem, data.data)
        else:
            self.handle_unknown(pktItem, data.data)
    
    def handle_tcp(self, pktItem, data):
        pktItem.src_port = data.sport
        pktItem.dst_port = data.dport
        pktItem.protocol = "TCP"
        self.statistics.tcp += 1
    
    def handle_udp(self, pktItem, data):
        pktItem.src_port = data.sport
        pktItem.dst_port = data.dport
        pktItem.protocol = "UDP"
        self.statistics.udp += 1
    
    def handle_icmp(self, pktItem, data):
        pktItem.protocol = "ICMP"
        self.statistics.icmp += 1
    
    def handle_igmp(self, pktItem, data):
        pktItem.protocol = "IGMP"
        self.statistics.igmp += 1
    
    def handle_icmpv6(self, pktItem, data):
        pktItem.protocol = "ICMPv6"
        self.statistics.icmpv6 += 1
    
    def handle_unknown(self, pktItem, data):
#        pktItem.protocol = data.__class__.__name__
#        if pktItem.protocol == 'str':
#            pktItem.protocol = 'Unknown'
        self.statistics.unknown += 1
    
    def handle_error(self, pktItem):
        pktItem.info = 'error occur in %s() while processing the packet' % inspect.stack()[2][3]
        self.statistics.error += 1
    

    def show_item(self, item):
#        table = self.pktTableWidget
        row = self.table.rowCount()
        self.table.insertRow(row)
        
        source = item.src_ip
        if source == None:
            source = item.src_mac
        destination = item.dst_ip
        if destination == None:
            destination = item.dst_mac
        
        if item.protocol == 'TCP' or item.protocol == 'UDP':
            source += ':' + str(item.src_port)
            destination += ':' + str(item.dst_port)

        
        No = QtGui.QTableWidgetItem(QtCore.QString(str(row + 1)))
        No.setFlags(No.flags() ^ QtCore.Qt.ItemIsEditable)
        self.table.setItem(row, 0, No)
        
        Time = QtGui.QTableWidgetItem(QtCore.QString(item.time))
        Time.setFlags(Time.flags() ^ QtCore.Qt.ItemIsEditable)
        self.table.setItem(row, 1, Time)
        
        Source = QtGui.QTableWidgetItem(QtCore.QString(source))
        Source.setFlags(Source.flags() ^ QtCore.Qt.ItemIsEditable)
        self.table.setItem(row, 2, Source)
        
        Destination = QtGui.QTableWidgetItem(QtCore.QString(destination))
        Destination.setFlags(Destination.flags() ^ QtCore.Qt.ItemIsEditable)
        self.table.setItem(row, 3, Destination)
        
        Protocol = QtGui.QTableWidgetItem(QtCore.QString(item.protocol))
        Protocol.setFlags(Protocol.flags() ^ QtCore.Qt.ItemIsEditable)
        self.table.setItem(row, 4, Protocol)
        
        Length = QtGui.QTableWidgetItem(QtCore.QString(str(item.len)))
        Length.setFlags(Length.flags() ^ QtCore.Qt.ItemIsEditable)
        self.table.setItem(row, 5, Length)

    
        
<file_sep>/QSniffer.py
from MainWindow import MainWindow, pyqtSignature
from Capturer import Capturer, WIN32
from PyQt4 import QtCore, QtGui
from Analyzer import Analyer
from Util import PktList, ProtocolTree, PktContent
import sys, threading, shutil, os

class QSniffer(MainWindow):
    def __init__(self):
        MainWindow.__init__(self)
        
        self.pktList = PktList()
        
        self.capturer = Capturer(self.pktList)
        self.cap_thread = None
        self.analyzer = Analyer(self.pktList, self.pktTableWidget, self)
        self.ana_thread = None
        
        MainWindow.set_devlist(self, self.capturer.devlist, WIN32)
#        self.testWidget()
        self.show()
    
    @pyqtSignature("int")
    def on_promisCheckBox_stateChanged(self, p0):
        MainWindow.on_promisCheckBox_stateChanged(self, p0)
#        print "check int:%d"%p0
        if(self.promisCheckBox.isChecked()):
            self.capturer.set_promisc(True)
        else:
            self.capturer.set_promisc(False)
    
    @pyqtSignature("")
    def on_startButton_clicked(self):
        MainWindow.on_startButton_clicked(self)
        if self.capturer.adhandle == None:
            curindex = self.devComboBox.currentIndex()
            if not self.capturer.open_dev(curindex):
#                TODO: handle open error
                return
        self.cap_thread = threading.Thread(target=self.capturer.start_capture)
        self.cap_thread.start()
        self.ana_thread = threading.Thread(target=self.analyzer.start_analize)
        self.ana_thread.start()
    
    @pyqtSignature("")
    def on_stopButton_clicked(self):
        MainWindow.on_stopButton_clicked(self)
        if self.cap_thread != None and self.cap_thread.is_alive():
            self.capturer.stop_capture()
            self.cap_thread.join()
        if self.ana_thread != None and self.ana_thread.is_alive():
            self.analyzer.stop_analize()
            self.ana_thread.join()
    
    @pyqtSignature("")
    def on_clearButton_clicked(self):
        MainWindow.on_clearButton_clicked(self)
        if self.cap_thread == None or self.ana_thread == None:
            pass
        elif self.cap_thread.is_alive() or self.ana_thread.is_alive():
            if self.capturer.pktSrcType == 'dev':
                QtGui.QMessageBox.information(self, "Information", 
                                              self.tr("You must stop capture first."))
                return False
            elif self.capturer.pktSrcType == 'dump':
                self.on_stopButton_clicked()
        
        self.capturer.clear()
        self.analyzer.clear()
        self.pktList.clear()
        
        count = self.pktTableWidget.rowCount()
        for i in range(count):
            self.pktTableWidget.removeRow(0)
        self.pktTreeWidget.clear()
        self.pktAsciiBrowser.clear()
        self.pkt0xBrowser.clear()
        return True
    
    @pyqtSignature("")
    def on_exportButton_clicked(self):
        MainWindow.on_exportButton_clicked(self)
        if self.cap_thread == None or self.ana_thread == None:
            pass
        elif self.cap_thread.is_alive() or self.ana_thread.is_alive():
            if self.capturer.pktSrcType == 'dev':
                QtGui.QMessageBox.information(self, "Information", 
                                              self.tr("You must stop capture first."))
                return False
            elif self.capturer.pktSrcType == 'dump':
                self.on_stopButton_clicked()
        
        fdialog = QtGui.QFileDialog()
        fdialog.setWindowTitle('Save pcap file')
        fname = fdialog.getSaveFileName(filter='pcap file(*.pcap)', directory='/')
        fname = unicode(fname)
        if str(fname) == '':
            return False
        if os.path.exists('~tmp'):
            shutil.move('~tmp', fname)
        return True
    
    @pyqtSignature("")
    def on_importButton_clicked(self):
        MainWindow.on_importButton_clicked(self)
        if not self.on_clearButton_clicked():
            return False
        
        fdialog = QtGui.QFileDialog()
        fdialog.setWindowTitle('Select pcap file')
        fname = fdialog.getOpenFileName(directory='/')
        fname = unicode(fname)
#        print "file name:%r" % fname
        
        if fname == '':
            return 
        if not self.capturer.open_dump(fname):
            return
        self.cap_thread = threading.Thread(target=self.capturer.start_capture)
        self.cap_thread.start()
        self.ana_thread = threading.Thread(target=self.analyzer.start_analize)
        self.ana_thread.start()
        
    @pyqtSignature("")
    def on_filterApplyButton_clicked(self):
        MainWindow.on_filterApplyButton_clicked(self)
        if self.capturer.adhandle == None:
            curindex = self.devComboBox.currentIndex()
            if not self.capturer.open_dev(curindex):
                return
        filterstr = str(self.filterLineEdit.text())
#        print "%r" % filterstr
        if filterstr == "":
            return 
        msg = self.filterMsgLable
        if self.capturer.compile_filter(filterstr):
            if self.capturer.set_filter():
                msg.setText(QtCore.QString("<font style='color: green;'>Success</font>"))
            else:
                msg.setText(QtCore.QString("<font style='color: red;'>Error occur</font>"))
        else:
            msg.setText(QtCore.QString("<font style='color: red;'>Wrong syntax</font>"))
    
    @pyqtSignature("")
    def on_filterClearButton_clicked(self):
        MainWindow.on_filterClearButton_clicked(self)
        self.filterLineEdit.clear()
    
    @pyqtSignature("QString")
    def on_filterLineEdit_textChanged(self, p0):
        MainWindow.on_filterLineEdit_textChanged(self, p0)
        self.filterMsgLable.clear()
    
    @pyqtSignature("int")
    def on_devComboBox_currentIndexChanged(self, index):
        MainWindow.on_devComboBox_currentIndexChanged(self, index)
        self.analyzer.statistics.updateStatistics(self)
#        print "combobox index:%d" % index
        
    @pyqtSignature("int, int")
    def on_pktTableWidget_cellClicked(self, row, column):
        MainWindow.on_pktTableWidget_cellClicked(self, row, column)
        tree = self.pktTreeWidget
        tree.clear()
        pktItem = self.analyzer.itemlist[row]
        pktdata = pktItem.rawpkt[1]
        
        pTree = ProtocolTree(tree, pktdata)
        tree.insertTopLevelItems(0, pTree.parseProtocol())
        p0xb = self.pkt0xBrowser
        p0xb.setText(QtCore.QString(PktContent.pkt0xContent(pktdata)))
        pasciib = self.pktAsciiBrowser
        pasciib.setText(QtCore.QString(PktContent.pktAsciiContent(pktdata)))
    
    def closeEvent(self, *args, **kwargs):
        if os.path.exists('./~tmp'):
            os.remove('./~tmp')
        self.on_stopButton_clicked()
        return MainWindow.closeEvent(self, *args, **kwargs)
    

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    qsniffer = QSniffer()
    
    sys.exit(app.exec_())
        
<file_sep>/Util.py
import threading, dpkt, socket
from PyQt4.QtCore import QString
from PyQt4.QtGui import QTreeWidgetItem

class Statistics:
    def __init__(self):
        self.ip = 0
        self.ipv6 = 0
        self.arp = 0
        self.rarp = 0
        self.tcp = 0
        self.udp = 0
        self.icmp = 0
        self.icmpv6 = 0
        self.igmp = 0
        self.error = 0
        self.unknown = 0
        self.total = 0
        
    def updateStatistics(self, window):
        window.totalCountLabel.setText(QString(str(self.total)))
        window.arpCountLabel.setText(QString(str(self.arp)))
        window.rarpCountLabel.setText(QString(str(self.rarp)))
        window.ipCountLabel.setText(QString(str(self.ip)))
        window.ipv6CountLabel.setText(QString(str(self.ipv6)))
        window.tcpCountLabel.setText(QString(str(self.tcp)))
        window.udpCountLabel.setText(QString(str(self.udp)))
        window.icmpCountLabel.setText(QString(str(self.icmp)))
        window.igmpCountLabel.setText(QString(str(self.igmp)))
        window.icmpv6CountLabel.setText(QString(str(self.icmpv6)))
        window.othersCountLabel.setText(QString(str(self.unknown)))
        window.errorCountLabel.setText(QString(str(self.error)))

class PktItem():
    def __init__(self):
        self.rawpkt = None
        self.time = None
        self.len = None
        self.protocol = None
        self.src_mac = None
        self.dst_mac = None
        self.src_ip = None
        self.dst_ip = None
        self.src_port = None
        self.dst_port = None
        self.info = None

class PktList():
    def __init__(self):
        self.pktlist = []
        self.mutex = threading.Lock()
    def clear(self):
        del self.pktlist[:]

class PktContent():
    def __init__(self):
        pass
    @staticmethod
    def pkt0xContent(pktdata):
        content = ''
        for i, c in enumerate(pktdata):
            content += '%-3.2x' % ord(c)
            if i % 8 == 7:
                content += '\n'
        return content
    
    @staticmethod
    def pktAsciiContent(pktdata):
        content = ''
        for i, c in enumerate(pktdata):
            if ord(c) < 0x20 or ord(c) > 0x7e:
                c = '.'
            content += '%c' % ord(c)
            if i % 8 != 7:
                content += ' '
            else:
                content += '\n'
        return content
            
        

class ProtocolTree():
    def __init__(self, fatherNode, pktdata):
        self.fatherNode = fatherNode
        self.pktdata = pktdata
        self.TreeList = []
        
    def parseProtocol(self):
        frame = dpkt.ethernet.Ethernet(self.pktdata)
        
        self.parseEthernetTree(self.fatherNode, frame)
        
        return self.TreeList
        
        
    def parseEthernetTree(self, fatherNode, frame):
        if frame.__class__.__name__ != 'Ethernet':
            print 'parseTree: error in parseEthernetTree. Classname is %s' % frame.__class__.__name__
            return None
        EthernetTree = QTreeWidgetItem(fatherNode)
        EthernetTree.setText(0, 'Ethernet')
        EthernetTup = (('dst', "Destination: %s" % NetFormat.ntoa_mac(frame.dst)),
                        ('src', "Source: %s" % NetFormat.ntoa_mac(frame.src)),
                        ('type', "Type: 0x%.4x" % frame.type)
                        )
        # TODO: explain the type code
        self.parseDetail(EthernetTree, EthernetTup)
        self.TreeList.append(EthernetTree)
        
        if frame.type == dpkt.ethernet.ETH_TYPE_ARP:
            self.parseARPTree(fatherNode, frame.data)
        elif frame.type == dpkt.ethernet.ETH_TYPE_IP:
            self.parseIPTree(fatherNode, frame.data)
        elif frame.type == dpkt.ethernet.ETH_TYPE_IP6:
            self.parseIPv6Tree(fatherNode, frame.data)
        else:
            self.parseUnknownTree(fatherNode, frame.data)

    def parseARPTree(self, fatherNode, arp):
        ARPTree = QTreeWidgetItem(fatherNode)
        ARPTree.setText(0, 'ARP')
        ARPTup = (('hrd', 'Hardware type: %d' % arp.hrd),
                ('pro', 'Protocol type: %d' % arp.pro),
                ('hln', 'Hardware length: %d' % arp.hln),
                ('pln', 'Protocol length: %d' % arp.pln),
                ('op', 'Opcode: %d' % arp.op),
                ('sha', 'Sender MAC address: %s' % NetFormat.ntoa_mac(arp.sha)),
                ('spa', 'Sender IP address: %s' % NetFormat.ntoa_ip(arp.spa)),
                ('tha', 'Target MAC address: %s' % NetFormat.ntoa_mac(arp.tha)),
                ('tpa', 'Target IP address: %s' % NetFormat.ntoa_ip(arp.tpa))
                )
        
        self.parseDetail(ARPTree, ARPTup)
        self.TreeList.append(ARPTree)

        
    def parseIPTree(self, fatherNode, ip):
        IPTree = QTreeWidgetItem(fatherNode)
        IPTree.setText(0, 'IP')
        IPTup = (('v', 'Version: %d' % ip.v),
                  ('hl', 'Header Length: %d' % (ip.hl << 4)),
                  ('tos', 'Differentiated Services: 0x%.2x' % ip.tos),
                  ('len', 'Total Length: %d' % ip.len),
                  ('id', 'Identification: 0x%.4x' % ip.id),
                  ('flag', 'Flags: 0x%.2x' % (ip.off >> 13)),
                  ('off', 'Fragment Offset: %d' % (ip.off & 0x1fff)),
                  ('ttl', 'Time To Live: %d' % ip.ttl),
                  ('p', 'Protocol: %d' % ip.p),
                  ('sum', 'Header Checksum: 0x%.4x' % ip.sum),
                  ('src', 'Source: %s' % NetFormat.ntoa_ip(ip.src)),
                  ('dst', 'Destination: %s' % NetFormat.ntoa_ip(ip.dst))
                  )
        
        self.parseDetail(IPTree, IPTup)
        self.TreeList.append(IPTree)
        
        if ip.p == dpkt.ip.IP_PROTO_TCP:
            self.parseTCPTree(fatherNode, ip.data)
        elif ip.p == dpkt.ip.IP_PROTO_UDP:
            self.parseUDPTree(fatherNode, ip.data)
        elif ip.p == dpkt.ip.IP_PROTO_ICMP:
            self.parseICMPTree(fatherNode, ip.data)
        elif ip.p == dpkt.ip.IP_PROTO_IGMP:
            self.parseIGMPTree(fatherNode, ip.data)
        else:
            self.parseUnknownTree(fatherNode, ip.data)
        
    
    def parseIPv6Tree(self, fatherNode, ipv6):
        IPv6Tree = QTreeWidgetItem(fatherNode)
        IPv6Tree.setText(0, 'IPv6')
        IPv6Tup = (('v', 'Version: %d' % ipv6.v),
                   ('fc', 'Traffic class: 0x%.8x' % ipv6.fc),
                   ('flow', 'Flow label: 0x%.8x' % ipv6.flow),
                   ('plen', 'Payload length: %d' % ipv6.plen),
                   ('nxt', 'Next header: %d' % ipv6.nxt),
                   ('hlim', 'Hop limit: %d' % ipv6.hlim),
                   ('src', 'Source: %s' % NetFormat.ntoa_ipv6(ipv6.src)),
                   ('dst', 'Destination: %s' % NetFormat.ntoa_ipv6(ipv6.dst))
                   )
        
        self.parseDetail(IPv6Tree, IPv6Tup)
        self.TreeList.append(IPv6Tree)
        
        if ipv6.p == dpkt.ip.IP_PROTO_TCP:
            self.parseTCPTree(fatherNode, ipv6.data)
        elif ipv6.p == dpkt.ip.IP_PROTO_UDP:
            self.parseUDPTree(fatherNode, ipv6.data)
        elif ipv6.p == dpkt.ip.IP_PROTO_ICMP6:
            self.parseICMPv6Tree(fatherNode, ipv6.data)
        else:
            self.parseUnknownTree(fatherNode, ipv6.data)
        
    
    def parseTCPTree(self, fatherNode, tcp):
        TCPTree = QTreeWidgetItem(fatherNode)
        TCPTree.setText(0, 'TCP')
        TCPTup = (('sport', 'Source port: %d' % tcp.sport),
                  ('dport', 'Destination port: %d' % tcp.dport),
                  ('seq', 'Sequence number: %d' % tcp.seq),
                  ('ack', 'Acknowledgment number: %d' % tcp.ack),
                  ('off_x2', 'Header length: %d' % tcp.off),
                  ('flags', 'Flags: 0x%.4x' % tcp.flags),
                  ('win', 'Window Size: %d' % tcp.win),
                  ('sum', 'Checksum: 0x%.4x' % tcp.sum),
                  ('urp', 'Urgent pointer: 0x%.4x' % tcp.urp)
                   )
        
        self.parseDetail(TCPTree, TCPTup)
        self.TreeList.append(TCPTree)
    
    def parseUDPTree(self, fatherNode, udp):
        UDPTree = QTreeWidgetItem(fatherNode)
        UDPTree.setText(0, 'UDP')
        UDPTup = (('sport', 'Source port: %d' % udp.sport),
                  ('dport', 'Destination port: %d' % udp.dport),
                  ('ulen', 'Length: %d' % udp.ulen),
                  ('sum', 'Checksum: 0x%.4x' % udp.sum)
                   )
                  
        self.parseDetail(UDPTree, UDPTup)
        self.TreeList.append(UDPTree)
    
    def parseICMPTree(self, fatherNode, icmp):
        ICMPTree = QTreeWidgetItem(fatherNode)
        ICMPTree.setText(0, 'ICMP')
        ICMPTup = (('type', 'Type: %d' % icmp.type),
                   ('code', 'Code: %d' % icmp.code),
                   ('sum', 'Checksum: 0x%.4x' % icmp.sum)
                    )
        
        self.parseDetail(ICMPTree, ICMPTup)
        self.TreeList.append(ICMPTree)
    
    def parseIGMPTree(self, fatherNode, igmp):
        IGMPTree = QTreeWidgetItem(fatherNode)
        IGMPTree.setText(0, 'IGMP')
        IGMPTup = (('type', 'Type: 0x%.2x' % igmp.type),
                   ('maxresp', 'Max Resp Code: %d' % igmp.maxresp),
                   ('sum', 'Checksum: 0x%.4x' % igmp.sum),
                   ('group', 'Group Address: %d' % igmp.group)
                    )
        
        self.parseDetail(IGMPTree, IGMPTup)
        self.TreeList.append(IGMPTree)
    
    def parseICMPv6Tree(self, fatherNode, icmpv6):
        ICMPv6Tree = QTreeWidgetItem(fatherNode)
        ICMPv6Tree.setText(0, 'ICMPv6')
        ICMPv6Tup = (('type', 'Type: %d' % icmpv6.type),
                     ('code', 'Code: %d' % icmpv6.code),
                     ('sum', 'Checksum: 0x%.4x' % icmpv6.sum)
                      )
        
        self.parseDetail(ICMPv6Tree, ICMPv6Tup)
        self.TreeList.append(ICMPv6Tree)
        
    def parseUnknownTree(self, fatherNode, data):
        UnknownTree = QTreeWidgetItem(fatherNode)
        UnknownTree.setText(0, 'Other parts')
    
    def parseDetail(self, fatherNode, Tuple):
        for t in Tuple:
            node = QTreeWidgetItem(fatherNode)
            node.setText(0, t[1])
    
        
        
class NetFormat():
    def __init__(self):
        pass
    
    @staticmethod
    def ntoa_mac(nmac):
        return '%.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(map(ord, list(nmac)))
    
    @staticmethod
    def ntoa_ip(nip):
        return '%d.%d.%d.%d' % tuple(map(ord, list(nip)))
    
    @staticmethod
    def ntoa_ipv6(nipv6):
        # TODO: format the ipv6 address
        addr = '%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x' % tuple(map(ord, list(nipv6)))
        return socket.getnameinfo((addr, 0), socket.NI_NUMERICHOST)[0]

<file_sep>/Capturer.py
from ctypes import *
from winpcapy import *
import time, platform, copy, os
from Util import PktList


if platform.python_version()[0] == "3":
    raw_input = input

errbuf = create_string_buffer(PCAP_ERRBUF_SIZE)
#header = POINTER(pcap_pkthdr)()
#pkt_data = POINTER(c_ubyte)()
class Capturer():
    def __init__(self, pktList):
        self.pktList = pktList      # packet list
        self.devlist = []           # device list
        self.__ispromisc = False      # promisc flag
        self.ifindex = 0            # choosed interface
        self.adhandle = None        # interface handler
        self.filter = ""            # filter string
        self.fcode = bpf_program()   # filter code
        self.goon = False
                
        self.pktSrcType = None  #pkt source type
        
        self.get_device_list()
    
    def get_device_list(self):
        """ get the device list. return bool to indicate success or not. """
        alldevs = POINTER(pcap_if_t)()
        ## Retrieve the device list
        if (pcap_findalldevs(byref(alldevs), errbuf) == -1):
            print ("Error in pcap_findalldevs: %s\n" % errbuf.value)
            return False

        i = 0
        try:
            d = alldevs.contents
        except:
            print ("Error in pcap_findalldevs: %s" % errbuf.value)
            print ("Maybe you need admin privilege?\n")
            return False
        while d:
            i = i + 1
            self.devlist.append(d)
            if d.next:
                d = d.next.contents
            else:
                d = False
        
        if (i == 0):
            print ("\nNo interfaces found! Make sure WinPcap is installed.\n")
        return True
    
    def print_device_list(self):
        if len(self.devlist) == 0:
            print "No interfaces found!"
        else:
            for i, d in enumerate(self.devlist):
                print("%d. %s" % (i + 1, d.name))
                if (d.description):
                    print (" (%s)\n" % (d.description))
                else:
                    print (" (No description available)\n")
    
    def set_promisc(self, ispromisc=False):
        self.__ispromisc = ispromisc
        print "promisc: %r" % self.__ispromisc
    
    def open_dump(self, filename):
        fname = create_string_buffer(filename)
        self.adhandle = pcap_open_offline(fname, errbuf)
        if self.adhandle == None:
            return False
        self.pktSrcType = 'dump'
        return True
        
    def open_dev(self, ifindex):
        self.ifindex = ifindex
        if(len(self.devlist) == 0):
            print "\nNo device in the device list!\n"
            return False
        if(self.ifindex < 0 or self.ifindex >= len(self.devlist)):
            print ("\nInterface number(%d) out of range(%d).\n" % (self.ifindex, len(self.devlist)))
            return False
        d = self.devlist[self.ifindex]

        self.adhandle = pcap_open_live(d.name, 65536, int(self.__ispromisc), 1000, errbuf)
        if (self.adhandle == None):
            print("\nUnable to open the adapter. %s is not supported by Pcap-WinPcap\n" % d.name)
            return False
        self.pktSrcType = 'dev'
        return True
    
    def compile_filter(self, filterstr=""):
        self.filter = filterstr
        netmask = 0xffffff
        if pcap_compile(self.adhandle, byref(self.fcode), self.filter, 1, netmask) < 0:
            print('\nError compiling filter: wrong syntax.\n')
            return False
        return True
            
    def set_filter(self):
        if pcap_setfilter(self.adhandle, byref(self.fcode)) < 0:
            print('\nError setting the filter\n')
            return False
        return True
    
    def start_capture(self):
        res = 1
        self.goon = True
        #********dump to tmp file
        self.dumpfile = pcap_dump_open(self.adhandle, '~tmp')
        if(self.dumpfile == None):
            print 'temp file open error'
        #**************
        while res >= 0 and self.goon:
            header = POINTER(pcap_pkthdr)()
            pkt_data = POINTER(c_ubyte)()
            res = pcap_next_ex(self.adhandle, byref(header), byref(pkt_data))
            if res == 0:
                print "timeout"
                continue
            if res == -2:
                break
            
            self.pktList.mutex.acquire()
            self.pktList.pktlist.append((copy.deepcopy(header.contents),
                                 buffer(bytearray(pkt_data[:header.contents.len]))))

            self.pktList.mutex.release()
            #.........dump
            pcap_dump(self.dumpfile, header, pkt_data)
            #..............
            
        if res == -1:
            print("Error reading the packets: %s\n", pcap_geterr(self.adhandle));
            pcap_close(self.adhandle)
            return False
        
        pcap_close(self.adhandle)
        pcap_dump_close(self.dumpfile)
        self.adhandle = None
        
        return True
    
    def stop_capture(self):
        self.goon = False
        pcap_dump_close(self.dumpfile)
    
    def clear(self):
        if os.path.exists('./~tmp'):
            os.remove('./~tmp')
        pass
    
    def print_pkts(self):
        for h, d in self.pktList.pktlist:
            local_tv_sec = h.ts.tv_sec
            ltime = time.localtime(local_tv_sec);
            timestr = time.strftime("%H:%M:%S", ltime)
            print
            print("%s,%.6d len:%d" % (timestr, h.ts.tv_usec, h.len))


if __name__ == '__main__':
    cap = Capturer(PktList())
    

        
<file_sep>/README.txt
QSniffer

1. 若要在Python环境中运行QSniffer，则需要安装如下依赖模块：
  1）winpcapy
    https://code.google.com/p/winpcapy/
  2) dpkt
    https://code.google.com/p/dpkt/
  3) Qt4
    http://qt-project.org/downloads
  4) PyQt4
    http://www.riverbankcomputing.co.uk/software/pyqt/download

2. 打包好的QSniffer.exe可在32位Windows上执行(见可执行程序文件夹)。不需要安装Python运行环境及上述各依赖库。
	<file_sep>/MainWindow.py
# -*- coding: utf-8 -*-

"""
Module implementing MainWindow.
"""

from PyQt4.QtGui import QMainWindow, QApplication
from PyQt4.QtCore import pyqtSignature, QStringList, QString
from PyQt4.QtGui import QTableWidget
from Ui_QSniffer import Ui_MainWindow

class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent = None):
        """
        Constructor
        """
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
        
        self.pktTableWidget.setColumnWidth(0,50)
        self.pktTableWidget.setColumnWidth(1,75)
        self.pktTableWidget.setColumnWidth(2,150)
        self.pktTableWidget.setColumnWidth(3,150)
        self.pktTableWidget.setColumnWidth(4,65)
        self.pktTableWidget.setColumnWidth(5,60)
        self.pktTableWidget.setColumnWidth(6,160)
        self.pktTableWidget.setEditTriggers(QTableWidget.NoEditTriggers)
        self.pktTableWidget.setSelectionBehavior(QTableWidget.SelectRows)
        self.pktTableWidget.setSelectionMode(QTableWidget.SingleSelection)
        self.pktTableWidget.setAlternatingRowColors(True)
        
        self.pktTreeWidget.setHeaderHidden(True)
    
    def set_devlist(self, devlist, isWIN32):
        qslist = QStringList()
        if isWIN32:
            for dev in devlist:
                qslist.append(QString(dev.description))
        else:
            for dev in self.capturer.devlist:
                qslist.append(QString(dev.name))
        self.devComboBox.addItems(qslist)
    
    @pyqtSignature("")
    def on_filterApplyButton_clicked(self):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("")
    def on_filterClearButton_clicked(self):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("")
    def on_stopButton_clicked(self):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("")
    def on_startButton_clicked(self):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("")
    def on_clearButton_clicked(self):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("")
    def on_exportButton_clicked(self):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("")
    def on_importButton_clicked(self):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("int")
    def on_promisCheckBox_stateChanged(self,p0):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("QString")
    def on_filterLineEdit_textChanged(self, p0):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("int")
    def on_devComboBox_currentIndexChanged(self, index):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("QModelIndex")
    def on_pktTableWidget_activated(self, index):
        """
        Slot documentation goes here.
        """
        pass
    
    @pyqtSignature("int, int")
    def on_pktTableWidget_cellClicked(self, row, column):
        """
        Slot documentation goes here.
        """
        pass
    

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    mainWindow = MainWindow()

    mainWindow.show()
    sys.exit(app.exec_())   
