2013-03-13 44 views
1

这是我使用的代码。这是我从互联网上获得的代码,他们说它工作正常。对此的评论也很好,但我不明白为什么它不适合我。还有一件事我使用这个应用程序作为用户模式不是在管理员模式。C#套接字例外:尝试以访问权限的方式访问套接字

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 
       Console.WriteLine("1"); 
       mainSocket = new Socket(AddressFamily.InterNetwork, 
        SocketType.Raw, ProtocolType.IP); 
       Console.WriteLine("2"); 
       //Bind the socket to the selected IP address 
       mainSocket.Bind(new IPEndPoint(IPAddress.Parse(cmbInterfaces.Text), 0)); 
       Console.WriteLine("3"); 
       //Set the socket options 
       mainSocket.SetSocketOption(SocketOptionLevel.IP,   //Applies only to IP packets 
              SocketOptionName.HeaderIncluded, //Set the include the header 
              true);       //option to true 
       Console.WriteLine("4"); 
       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 (SocketException ex) 
     { 
      Console.WriteLine("5"); 
      MessageBox.Show(ex.Message, "MJsniffer", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("6"); 
      MessageBox.Show(ex.Message, "MJsniffer", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 
+1

哪行代码导致的问题标题中提到的例外呢? – stakx 2013-03-13 07:28:05

回答

0

你能检查SocketException.SocketErrorCode并更新你的问题吗?
我假设你收到10013 - 这些是code descriptions。 最有可能或者一些其他的应用程序已经访问套接字或您的权限丢失,

4

还有一件事我使用不是在管理员模式下,该应用程序为用户模式。

这是行不通的。该following是针对WIN32 API编写的,但因为这就是.NET呼吁下到上,同样适用:

要使用类型的插座SOCK_RAW需要管理员权限。运行使用原始套接字的Winsock应用程序的用户必须是本地计算机上的管理员组的成员,否则原始套接字调用将失败,错误代码为WSAEACCES。在Windows Vista和更高版本上,创建套接字时会强制访问原始套接字。在Windows的早期版本中,在其他套接字操作期间强制访问原始套接字。

我的重点

相关问题