Reputation: 610
A bit of context: For study/practice, I'm working on a network application and I noticed that the socket only correctly opens if I provide an IPv4 address to people whose public IP is IPv4 and IPv6 for those whose public IP is IPv6.
I thought to select filter the right one by using something kindred to the following:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
public class Test {
public static void main(String[] args) throws MalformedURLException, IOException {
BufferedReader ipTypeChecker = new BufferedReader(
new InputStreamReader(
new URL("https://wtfismyip.com/text").openStream()
)
);
System.out.println(ipTypeChecker.readLine());
}
}
If I simply google What is my ip, go to this page or this page, My IP is shown as an IPv6 address, yet if I query those pages using the above code it returns an IPv4 address, why?
Of course, if I am suffering from the XY problem feel free to point out where I've gone wrong.
Upvotes: 2
Views: 361
Reputation: 123501
According to the documentation Java prefers IPv4 addresses to IPv6 addresses if both are available:
java.net.preferIPv6Addresses (default: false)
If IPv6 is available on the operating system the default preference is to prefer an IPv4-mapped address over an IPv6 address. This is for backward compatibility reasons...
The target host has both types of address:
wtfismyip.com. 3600 IN AAAA 2604:4300:a:2c::1:1
wtfismyip.com. 3600 IN A 69.30.217.90
This means Java will pick the IPv4 address. Browsers will instead prefer IPv6 usually.
Upvotes: 4