C#监听80端口

标签 c#

我想监听 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。

MSDN Socket Error Codes

有关更多详细信息,请将 server.Start() 调用包装在 try/catch 中并捕获 SocketException 并检查 SocketException.ErrorCode。

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

MSDN TcpListener.Start()

关于C#监听80端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10506069/

相关文章:

c# - Asp.net 比较验证器以验证日期

c# - WebClient 在 Windows 8.1 中下载损坏的文件

c# - 引用一个命名空间,而当前命名空间中有一个相同的命名空间

c# - MonoTouch - 从 Jenkins 运行 mdtool

c# - 使用 NameValueCollection 类存储两个以上的值

c# - 如何在html表格中将水平行更改为垂直列数据显示

c# - 动态创建方法,其中返回类型在编译时已知

C# 读取进程内存 : How to read a 64 bit memory address?

c# - Azure 实例更改已删除的文件

c# - 只有无参数的基类构造函数是好的设计实践吗?