c#套接字异常:试图以套接字访问权限禁止的方式访问套接字
本文关键字:套接字 访问 访问权 权限 方式 禁止 异常 | 更新日期: 2023-09-27 18:03:33
这是我使用的代码。这是我从网上得到的代码,他们说运行正常。这个评论也很好,但我不明白为什么它不适合我。还有一件事,我是在用户模式下使用这个应用程序的,而不是在管理员模式下。
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);
}
}
还有一件事,我是在用户模式下使用这个应用程序的,而不是在管理员模式下。
这不能工作。以下是为Win32 api编写的,但由于这是。net调用的内容,因此同样适用:
使用
SOCK_RAW
类型的套接字需要管理员权限。使用原始套接字的Winsock应用程序的用户必须是本地计算机上Administrators组的成员,否则原始套接字调用将失败,错误码为WSAEACCES
。在Windows Vista及更高版本中,对原始套接字的访问在套接字创建时强制执行。在早期版本的Windows中,对原始套接字的访问是在其他套接字操作期间强制执行的。
(我强调)
是否可以检查SocketException。SocketErrorCode和更新你的问题?
我假设你收到的是10013 -这些是代码描述。很可能是其他应用程序正在访问套接字,或者您的权限缺失,