简体   繁体   中英

Using ipv6 address to connect to a server using HttpClient (using ipv6 address to define URI) Fixing - Invalid URI: Invalid port specified)

I have simple HttpClient which works perfectly when using ipv4/fqdb/host names (please see below for code snippet). However same code doesn't work, the moment I tried to use ipv6 address to connect to server. I probably need to change some configuration settings and able to define uri with ipv6 address.

I have looked at msdn and it has the following statement:

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

Not sure what it means, will try to figure it out.

What can I try to fix the problem?

Looks like I need to keep ipv6 address in square brackets [enclose it '[]'] http://[fe08::83e7:71e8:1364:0dff%19]:58703/ and looks like everything is working OK now. thanks to How to include ipv6 addresses with (or without) zone indexes in uri for .net remoting?

Code:

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"));

You need to specify the URI in the format specified by RFC 2732 . Basically, wrap the actual IPv6 address in square brackets.

The ScopeId you mention is the "%19" part of your example URI. The very high-level, hand-waving description is "it basically identifies which network interface the address corresponds to on the local machine." This Super User post and this MSDN article have reasonably understandable detailed descriptions of what it actually means, if you're interested.

In your case, all you really need to know is that it's meaningless/misleading to include it in a BaseAddress property because the value is only meaningful for your specific machine. It doesn't make sense to send it out in HTTP responses since the value has no meaning for remote clients. That's why, as the documentation you mention points out, HttpClient won't use it even if you include it in the BaseAddress.

The final updated URI would look like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM