使用此代码,我只能嗅到本地流量(向内)我该如何嗅探所有流量(向外)
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);
答案 0 :(得分:1)
不确定您是否对第三方库感兴趣,但您可以使用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.");
请注意,收到的数据包意味着WinPCap收到的数据包。它不表示数据包的方向。这包括入站和出站流量,您可以通过源IP和目标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
答案 1 :(得分:0)