gpt4 book ai didi

c# - .NET 权限异常中的网络数据包嗅探

转载 作者:行者123 更新时间:2023-12-03 21:52:03 24 4
gpt4 key购买 nike

我有一本名为《Network Programming in .NET》的书,其中包含以下用于嗅探网络堆栈上的 IP 数据包的代码示例。我已经从书中复制了代码示例 WORD-FOR-WORD,所以请原谅缺乏文体约定等。

List<string> packets = new List<string>();

public void Run()
{
int len_receive_buf = 4096;
int len_send_buf = 4096;
byte[] receive_buf = new byte[len_receive_buf];
byte[] send_buf = new byte[len_send_buf];
int cout_receive_bytes;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
socket.Blocking = false;
IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName());
socket.Bind(new IPEndPoint(IPAddress.Parse(IPHost.AddressList[0].ToString()), 0));
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
byte[] IN = new byte[4] { 1, 0, 0, 0 };
byte[] OUT = new byte[4];
int SIO_RCVALL = unchecked((int)0x98000001);
int ret_code = socket.IOControl(SIO_RCVALL, IN, OUT);
while(true)
{
IAsyncResult ar = socket.BeginReceive(receive_buf, 0, len_receive_buf, SocketFlags.None, null, this);
cout_receive_bytes = socket.EndReceive(ar);
Receive(receive_buf, cout_receive_bytes);
}
}

public void Receive(byte[] buf, int len)
{
if(buf[9] == 6)
{
packets.Add(Encoding.ASCII.GetString(buf).Replace("\0", " "));
}
}

我第一次测试它是几年前(甚至在 Vista 出现之前),我使用的机器是一个 32 位 Windows XP Professional 平台,带有一个在 IPv4 上运行的 NIC。

我现在正尝试在 64 位 Windows 7 平台上进行测试,该平台具有运行 IPv6 的 NIC,但它无法正常工作。我假设这与 IPv6 有关。谁能建议我如何有效地解决这个问题?

编辑:这是我尝试运行时遇到的异常...

enter image description here

最佳答案

header 在 IPv4 之间明显不同和 IPv6 .

所以检查:

if(buf[9] == 6)

检查数据包是否为 IPv4 的 TCP 是查询 IPv6 数据包的部分源地址字段。对于 IPv6,它应该检查偏移量 6* 处的“Next Header”。当然,现在还需要先查看IP版本,才能知道是查看offset 6还是offset 9。


对于异常消息,您可能没有以管理员身份运行,您需要以管理员身份运行 raw sockets ( native 文档,但仍然适用):

To use a socket of type SOCK_RAW requires administrative privileges. Users running Winsock applications that use raw sockets must be a member of the Administrators group on the local computer, otherwise raw socket calls will fail with an error code of WSAEACCES. On Windows Vista and later, access for raw sockets is enforced at socket creation. In earlier versions of Windows, access for raw sockets is enforced during other socket operations.


(*) 当然,在您发现它是一个 TCP 数据包之前,可能需要处理多个 IPv6 header 。

关于c# - .NET 权限异常中的网络数据包嗅探,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12348475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com