Sniffer ERROR:“试图以其访问权限禁止的方式访问套接字”

时间:2015-01-04 18:45:49

标签: c# sockets packet-sniffers sniffer

当我试图嗅探时,我遇到了这个问题,我确实用addressFamily声明了一个RAW_SOCKET,但我不知道我的问题是什么

private void btnStart_Click(object sender, EventArgs e)
{
    if (cmbInterfaces.Text == "")
    {
        MessageBox.Show("Select an Interface to capture the packets.", "MJsniffer", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }
    try
    {
        if (!bContinueCapturing)        
        {
            //Start capturing the packets...

            btnStart.Text = "&Stop";

            bContinueCapturing = true;

            //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 Socket(AddressFamily.InterNetwork,
                SocketType.Raw, ProtocolType.IP);

            //Bind the socket to the selected IP address
            mainSocket.Bind(new IPEndPoint(IPAddress.Parse(cmbInterfaces.Text), 0));

            //Set the socket  options
            mainSocket.SetSocketOption(SocketOptionLevel.IP,            //Applies only to IP packets
                                       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(IOControlCode.ReceiveAll,              //Equivalent to SIO_RCVALL constant
                                                                        //of Winsock 2
                                 byTrue,                                    
                                 byOut);

            //Start receiving the packets asynchronously
            mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
                new AsyncCallback(OnReceive), null);
        }
        else
        {
            btnStart.Text = "&Start";
            bContinueCapturing = false;
            //To stop capturing the packets close the socket
            mainSocket.Close ();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "MJsniffer", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

基本上就是开始嗅探按钮

1 个答案:

答案 0 :(得分:0)

这是设计作为安全措施。您可以通过以“管理员”身份运行应用程序来规避这一点。在Windows上使用原始套接字还有其他限制。

有关原始套接字的更多信息:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms740548%28v=vs.85%29.aspx

Winpcap可以更灵活地用于嗅探器。 winpca还有一个c#包装器

http://pcapdotnet.codeplex.com/