Bastian
Bastian

Reputation: 391

HttpURLConnection and INetAddress using hostname fails while IPv6 works fine

so initially, i wanted to access a file via HTTP GET using a URL like "http://myhostname:123/path/to/file". My Browser could access it without any problems, so the next step was to get it out of java code.

    URL url = new URL("http","myhostname",123,"path/to/file");
    URLConnection openConnection = url.openConnection();
    HttpURLConnection asHttp = (HttpURLConnection) openConnection;
    assertEquals(200, asHttp.getResponseCode());

Sadly, I was running into a timeout. I was sniffing with Wireshark and couldn't see the request going over the wire.

Then i tried the exact same URL with IPv6 address and i could see the request going over the wire, but the server answered with HTTP 400 because he didn't liked not seeing "myhostname" written into the header.

InetAddress.getByName("myhostname").isReachable(5000) wasn't working as well, but works with IPv6. When using the ping command on cmd.exe, i can successfully ping with "ping myhostname". I've got some C#-code which runs also fine when using "myhostname". But why is it not working in Java and what do i need to do to make it functioning?

Note: The host i want to get access to is a virtual machine running on my pc. Since i'm not experienced in network programming it could be a simple thing that i am missing.

Upvotes: 1

Views: 1649

Answers (1)

Bastian
Bastian

Reputation: 391

Well, i could solve my problem:

As @Andreas suggested i tried ping -4 myhostname and an IPv4 address was resolved, but the ping timed out. I solved the problem by editing the host-file in C:\Windows\System32\drivers\etc and added the line 1234::1234:1234:1234:1234%2 myhostname. I recheckd with ping -4 myhostname but now it didn't resolved an address while ping myhostname works fine using IPv6. My Java Code was running perfectly right away.

I also retried using System.setProperty("java.net.preferIPv6Addresses", "true"); and it worked out of a simple main()-method, but it wasn't working out of a JUnit-Test.

Upvotes: 1

Related Questions