问题描述
我试图捕捉到的IP数据包在C#。
一切工作正常,但我只得到传出的数据包
I am trying to capture ip packets in c#.Everything is working fine, except that i only get outgoing packets.
我的代码:
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP))
{
sock.Bind(new IPEndPoint(MYADDRESS, 0));
sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
sock.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), null);
while (true)
{
byte[] buffer = new byte[sock.ReceiveBufferSize];
int count = sock.Receive(buffer);
// ...
}
}
这个问题肯定是我的电脑!但是,也许有一个解决办法...
The problem is definitely my pc! But maybe there is a workaround ...
推荐答案
我相信问题是,你绑定到回送IP,假设在你的代码'localhost'的暗示127.0.0.1。尝试绑定到要捕获的数据包的接口的IP地址。
I believe the problem is that you are binding to the loopback IP, assuming that 'LOCALHOST' in your code implies 127.0.0.1. Try binding to the IP address of the interface you want to capture the packets for.
我把你的代码做了一个快速测试,并且肯定我看到这两个流动数据方向,使用Windows 7的 NB 我运行这个作为管理员,不知道它有多好作品,否则。
I took your code an did a quick test, and definately I see data flowing in both directions, using Windows 7. NB I am running this as Administrator, not sure how well it works otherwise.
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP))
{
sock.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.121"), 0));
sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
sock.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), null);
while (true)
{
byte[] buffer = new byte[sock.ReceiveBufferSize];
int count = sock.Receive(buffer);
IpHeader hdr = IpHeader.FromPacket(buffer, count);
if ((ProtocolType)hdr.Protocol == ProtocolType.Tcp)
{
Console.WriteLine("{0} : {1} -> {2}", (ProtocolType)hdr.Protocol, new IPAddress(hdr.SrcAddr).ToString(), new IPAddress(hdr.DestAddr).ToString());
}
}
}
的图书馆,我用快速解码包为确保我在两个方向上看到的数据。
IpHeader is from a library I wrote years ago, I used that to quickly decode the packets to ensure I was seeing data in both directions.
下面是从代码的快速捕获上述验证(AA.BB.CC.DD是我的公网IP)
Here is a quick capture from the code above to verify (AA.BB.CC.DD is my public IP)
Tcp : 83.221.14.72 -> AA.BB.CC.DD
Tcp : AA.BB.CC.DD -> 83.221.14.72
Tcp : 83.221.14.72 -> AA.BB.CC.DD
Tcp : 83.221.14.72 -> AA.BB.CC.DD
Tcp : AA.BB.CC.DD -> 83.221.14.72
Tcp : 83.221.14.72 -> AA.BB.CC.DD
Tcp : 83.221.14.72 -> AA.BB.CC.DD
Tcp : AA.BB.CC.DD -> 83.221.14.72
Tcp : AA.BB.CC.DD -> 83.221.14.72
Tcp : AA.BB.CC.DD -> 83.221.14.72
Tcp : 83.221.14.72 -> AA.BB.CC.DD
Tcp : 83.221.14.72 -> AA.BB.CC.DD
Tcp : AA.BB.CC.DD -> 83.221.14.72
这篇关于插座将ReceiveAll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!