如何在 C# 中的 webclient 对象上绑定特定端口

How to bind a specific port on a webclient object in C#

我在做P2P应用,想用打孔技术连接点。 这是我的 PHP 第三方服务器脚本。

<?php
echo "{yourIP:'".$_SERVER['REMOTE_ADDR']."',yourPort:".$_SERVER['REMOTE_PORT']."}";
?>

在我的 C# 代码中,我创建了一个侦听 8765 的服务器套接字,当我想获取我的 public IP 地址和端口号(以便与同行共享)时,我向php 服务器使用 WebClient 对象。问题是 webclient 对象使用随机本地端口来发出请求。 如何将 webclient 对象绑定到 8765 端口?这样请求总是使用这个端口作为源端口。 谢谢!

对不起我的英语不好! :)

您将无法使用 WebClient 实现此目的,但是您可以使用 HttpWebRequest 解决它:

public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
    Console.WriteLine("BindIPEndpoint called");
      return new IPEndPoint(IPAddress.Any,5000);

}

public static void Main()
{

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://MyServer");

    request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

}