嗅探器 c# (outwar)

Sniffer c# (outwar)

使用此代码,我只能嗅探本地流量(向内)如何嗅探所有流量(向外)

Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
_socket.Bind(new IPEndPoint(bindTo, 0));
_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);                           //option to true


byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
byte[] byOut = new byte[4];

_socket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);

不确定您是否对第三方库感兴趣,但您可以使用 SharpPCap,它封装了 WinPCap 调用。我建议阅读这篇文章以了解它可以做什么。

http://www.codeproject.com/Articles/12458/SharpPcap-A-Packet-Capture-Framework-for-NET

文章中的示例(已简化):

// Extract a device from the list
ICaptureDevice device = devices[i];

// Open the device for capturing
int readTimeoutMilliseconds = 1000;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

Console.WriteLine();
Console.WriteLine("-- Listening on {0}...",
    device.Description);

Packet packet = null;

// Keep capture packets using GetNextPacket()
while((packet=device.GetNextPacket()) != null )
{
    // Prints the time and length of each received packet
    DateTime time = packet.PcapHeader.Date;
    int len = packet.PcapHeader.PacketLength;
    Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
        time.Hour, time.Minute, time.Second,
        time.Millisecond, len);
}

// Close the pcap device
device.Close();
Console.WriteLine(" -- Capture stopped, device closed.");

注意这里的received packet是指WinPCap接收到的数据包。它不指示数据包的去向。这包括入站和出站流量,您可以通过源和目标 IP 来区分它们。

这需要您 运行 正在使用的任何机器都安装 WinPCap。 WinPCap 是 Wireshark 用来捕获数据包的工具。

编辑:如果你想使用原始套接字,试试这个:

        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

        if (_localIp != null)
            _socket.Bind(new IPEndPoint(_localIp, 0));
        _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
        var receiveAllOn = BitConverter.GetBytes(1);
        _socket.IOControl(IOControlCode.ReceiveAll, receiveAllOn, null);

        _socket.ReceiveBufferSize = (1 << 16);
        Read();

我没有直接处理这段代码,但它确实在使用并且似乎在工作:https://github.com/lunyx/CasualMeter/blob/master/NetworkSniffer/IpSnifferRawSocketSingleInterface.cs

还需要 运行 作为管理员并关闭 Windows 防火墙:https://github.com/lunyx/CasualMeter/pull/47

Windows 防火墙效果...所有代码都可以!