TCP调试错误C#

时间:2011-09-06 18:38:55

标签: c# tcp tcplistener

public Server([Optional, DefaultParameterValue(0x6c1)] int port, [Optional, DefaultParameterValue("127.0.0.1")] string ip)
{
    this.IP = IPAddress.Parse(ip);
    this.Port = port;
    this.listenerConnection = new TcpListener(this.IP, this.Port);
    this.listenerConnection.Start();
    this.listenerThread = new Thread(new ThreadStart(this.listen));
    this.listenerThread.Start();
}

是我的代码,它运行正常,但是当我调试它时,我收到消息:

  

指定的参数超出了有效值的范围。参数名称:port

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

那么,port超出有效值范围,介于IPEndPoint.MinPortIPEndPoint.MaxPort之间。

答案 1 :(得分:0)

您是否尝试过使用机器的IPAddress?您可以使用以下代码获取运行该应用程序的计算机的IPAddress:

IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
IPAddress localIpAddress = null;

forach(IPAddress address in host.AddressList)
{
    if(address.AddressFamily == AddressFamily.InterNetwork)
    {
          localIpAddress = address;
    }
}

TcpListener listener = new TcpListener(localIpAddress, port);
listener.Start();

此外,您可能需要考虑使用默认端口> 5000.由于有许多保留或已经由服务使用的0到5000之间的端口。