gpt4 book ai didi

c# - 使用 ipv6 地址连接到使用 HttpClient 的服务器(使用 ipv6 地址定义 URI)修复 - 无效的 URI : Invalid port specified)

转载 作者:行者123 更新时间:2023-11-30 14:11:36 25 4
gpt4 key购买 nike

我有一个简单的 HttpClient,它在使用 ipv4/fqdb/主机名时工作得很好(请参阅下面的代码片段)。但是,当我尝试使用 ipv6 地址连接到服务器时,相同的代码不起作用。我可能需要更改一些配置设置并能够使用 ipv6 地址定义 uri。

我查看了 msdn,它有以下声明:

If the host name is an IPv6 address, the canonical IPv6 address is used. ScopeId and other optional IPv6 data are removed - http://msdn.microsoft.com/en-us/library/system.uri.aspx

不知道是什么意思,会试着弄明白。

我可以尝试如何解决这个问题?

看起来我需要将 ipv6 地址放在方括号中 [将其括在 '[]'] http://[fe08::83e7:71e8:1364:0dff%19]:58703/看起来现在一切正常。感谢How to include ipv6 addresses with (or without) zone indexes in uri for .net remoting?

代码:

this.Client = new HttpClient();
**//below line throws UriFormatException (Invalid URI: Invalid port specified)**
this.Client.BaseAddress = new Uri(http://fe08::83e7:71e8:1364:0dff%19:58703/);
this.Client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/xml"));

//whereas below code works, when ipv4/fqdn is used...

this.Client = new HttpClient();
this.Client.BaseAddress = new Uri(10.0.0.1:58501);
this.Client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/xml"));

最佳答案

您需要以 RFC 2732 指定的格式指定 URI .基本上,将实际的 IPv6 地址括在方括号中。

您提到的 ScopeId 是示例 URI 的“%19”部分。非常高级的挥手描述是“它基本上识别地址对应于本地机器上的哪个网络接口(interface)”。 This Super User postthis MSDN article如果您有兴趣,可以对其实际含义进行合理易懂的详细描述。

在您的情况下,您真正​​需要知道的是将它包含在 BaseAddress 属性中是没有意义的/误导性的,因为该值仅对您的特定机器有意义。在 HTTP 响应中发送它没有意义,因为该值对远程客户端没有意义。这就是为什么,正如您提到的文档所指出的那样,即使您将它包含在 BaseAddress 中,HttpClient 也不会使用它。

最终更新的 URI 如下所示:

this.Client.BaseAddress = new Uri(@"http://[ef08::83e7:71e8:1364:0dff]:54502/");

关于c# - 使用 ipv6 地址连接到使用 HttpClient 的服务器(使用 ipv6 地址定义 URI)修复 - 无效的 URI : Invalid port specified),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19676265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com