【问题标题】:Is there a way to specify the local port to used in tcpClient?有没有办法指定在 tcpClient 中使用的本地端口?
【发布时间】:2011-02-21 15:03:12
【问题描述】:

我目前正在使用这个函数调用来创建我的 tcpClient:

clientSocket = new TcpClient("localhost", clientPort);

但是clientPort是服务器的端口。

有没有办法让我使用 tcpClient 指定客户端端口?

谢谢

【问题讨论】:

    标签: c# sockets


    【解决方案1】:

    constructor overload that takes an IPEndPoint 允许您将 TcpClient 的内部 Socket 绑定到特定端口:

    IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
    IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, clientPort);
    TcpClient clientSocket = new TcpClient(ipLocalEndPoint);
    clientSocket.Connect(remoteHost, remotePort);
    

    【讨论】:

    • 最近在测试中,需要使用稍微不同的线路进行连接:clientSocket.Client.Connect(remoteHost, remotePort); .使用 clientSocket.Connect 会改变我的 clientPort。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2020-09-15
    相关资源
    最近更新 更多