0

so I made a php script that returns the IP Address of the user, And when i open it on my browser it returns an IPV6 IP Address (If the user has IPV6 or it will return IPV4).

enter image description here

But when I make a URLConnection to the same link using Java, It outputs a IPV4.

enter image description here

This is the code I am using in my java application along with the URL to my website.

String ip = new JSONObject(new BufferedReader(new InputStreamReader(LynxClient.getConnection(new URL("https://lynxclient.com/getip.php")).getInputStream())).readLine()).getString("ip");
System.out.println(ip);


public static HttpsURLConnection getConnection(URL url) throws IOException {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("User-Agent", "Mozilla/4.76");
    conn.setUseCaches(false);
    return conn;
}

and here is my PHP Code for my website.

<?php
$ip = null;
if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
    $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

echo json_encode(array('ip' => $ip));

So my issue is the browser and my java application returns wrong IP Address, which I want both of them to be the same, I am not sure what is wrong here, I have checked some threads made on SO regarding this but none has helped me so far.

SamHoque
  • 2,978
  • 2
  • 13
  • 43
  • have you tried setting `java.net.preferIPv6Addresses` on your command line? see https://docs.oracle.com/javase/8/docs/technotes/guides/net/ipv6_guide/index.html – radai Sep 21 '19 at 06:14
  • @radai I am not using a command line program, I am using a swing executable. but no I didnt try that. but what if I prefer IPv6 and the user doesn't have that? will it use ivp4? – SamHoque Sep 21 '19 at 06:17
  • the docs seem to suggest yes (ipv4 would be used if no 6). you may also be able to set it at runtime but this question seems to suggest it wont work - https://stackoverflow.com/questions/9882357/how-to-set-java-net-preferipv4stack-true-at-runtime – radai Sep 21 '19 at 06:17
  • @radai Thanks, I'll try it and report the results. – SamHoque Sep 21 '19 at 06:19

0 Answers0