2012-05-08 97 views
1

我想監聽端口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(); 
     } 
    } 
} 
+1

你確定你沒有其他的東西在端口80上聽已經? – ametren

+4

你爲什麼使用80端口?這是默認使用的IIS端口。有了這麼多的其他可用,這似乎是一個奇怪的選擇。 –

+0

「但它不起作用」 - 比這更多的信息? – ChrisF

回答

2

我懷疑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,我相信。

MSDN Socket Error Codes

更爲詳細的信息,您的包裹server.Start()調用在一個try/catch和捕捉SocketException並檢查SocketException.ErrorCode。

try 
{ 
    server.Start(); 
} 
catch (SocketException exception) 
{ 
    Console.Write(exception.ErrorCode); 
} 

MSDN TcpListener.Start()

0

據我所知停止IIS,要通過端口80綁定TCP連接,您需要獲得管理員權限。 因此,您必須以管理員身份運行您的程序,並且您使用的HttpListener應正常工作。 嘗試添加到您的清單文件:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />