我想监听端口80.为此,我编写了一个TCP监听器并赋予其管理员权限。但它不起作用(失败)。C#监听80端口
这是错误:
An attempt was made to access a socket in a way forbidden by its access permissions
我的代码:
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上听已经? – ametren
你为什么使用80端口?这是默认使用的IIS端口。有了这么多的其他可用,这似乎是一个奇怪的选择。 –
“但它不起作用” - 比这更多的信息? – ChrisF