【问题标题】:How to bind a specific port on a webclient object in C#如何在 C# 中绑定 webclient 对象上的特定端口
【发布时间】:2016-04-03 13:48:06
【问题描述】:

我正在开发 P2P 应用程序,我想使用打孔技术来连接对等点。 这是我的 PHP 第三方服务器脚本。

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

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

对不起我糟糕的英语! :)

【问题讨论】:

  • 可能是重复的,找stackoverflow.com/a/4788019/62662
  • 我用的不是socket,而是webclient对象如何绑定webclient对象?使用socket需要引入一些http协议的概念

标签: c# webclient


【解决方案1】:

您将无法使用 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();

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2011-11-28
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2010-11-02
    相关资源
    最近更新 更多