我想監聽端口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