2012-05-08 98 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" />