1

我想使用 C# 嗅探数据包数据我需要它来嗅探所有类型的数据,而不仅仅是 HTTP

当我尝试这样做时,我收到此错误:

System.Net.Sockets.SocketException:尝试以 System.Net.Sockets.Socket 的 System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) 的访问权限禁止的方式访问套接字。绑定(端点本地EP)

public void StartCapture(string InterfaceIp)
{
        try
        {
                //Start capturing the packets...
                //For sniffing the socket to capture the packets has to be a raw socket, with the
                //address family being of type internetwork, and protocol being IP
                mainSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                    System.Net.Sockets.SocketType.Raw, System.Net.Sockets.ProtocolType.IP);
                //Bind the socket to the selected IP address
                mainSocket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(InterfaceIp), 0));
                //Set the socket  options
                mainSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.IP,            //Applies only to IP packets
                                           System.Net.Sockets.SocketOptionName.HeaderIncluded, //Set the include the header
                                           true);                           //option to true
                byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
                byte[] byOut = new byte[4] { 1, 0, 0, 0 }; //Capture outgoing packets
                //Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
                mainSocket.IOControl(System.Net.Sockets.IOControlCode.ReceiveAll,              //Equivalent to SIO_RCVALL constant
                    //of Winsock 2
                                     byTrue,
                                     byOut);

                //Start receiving the packets asynchronously
                mainSocket.BeginReceive(byteData, 0, byteData.Length, System.Net.Sockets.SocketFlags.None,
                    new AsyncCallback(OnReceive), null);
        }
        catch (Exception ex)
        {
            //Report Exception
        }
}

注意:我正在使用 ASP.Net 并且嗅探数据非常重要,而不仅仅是数据包的标头

我认为问题与没有访问套接字的正确权限有关,尽管使用模拟并没有解决问题

我找到了解决我的问题的方法,它与最近的实现有关,该实现限制绑定到受保护的套接字并限制为单个 IP 地址

这里有一些有趣的链接

http://msdn.microsoft.com/en-us/library/cc150667(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/ms740668%28v=VS.85%29.aspx

4

2 回答 2

1

If you are OK with using a library, SharpPcap is a nice one and it's very simple to use.

于 2012-04-29T20:51:55.797 回答
1

我正在尝试使用原始套接字。

我修复了这个错误,

System.Net.Sockets.SocketException:'试图以访问权限禁止的方式访问套接字'

只需在管理员模式下运行 Visual Studio。

于 2018-02-26T19:19:57.223 回答