我想监听 80 端口。为此,我编写了一个 TCP 监听器并赋予它管理员权限。但它不起作用(它失败了)。
这是错误:
An attempt was made to access a socket in a way forbidden by its access permissions
My code:
static void Main(string[] args)
{
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
if (hasAdministrativeRight == true)
{
TcpListener server;
Int32 port = 80;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
client.Close();
}
}
}
最佳答案
我怀疑端口 80 已被 IIS 或 Skype 使用。 您需要关闭它们或更改它们使用的端口。
运行此命令并找出哪个进程 (PID) 正在使用端口 80:
C:\> netstat -ano
Active Connections
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 4
如果 PID 指向系统进程(在我的例子中为 4),那么我相信那就是 IIS。
有关更多详细信息,请将 server.Start() 调用包装在 try/catch 中并捕获 SocketException 并检查 SocketException.ErrorCode。
try
{
server.Start();
}
catch (SocketException exception)
{
Console.Write(exception.ErrorCode);
}
关于C#监听80端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10506069/