Java getLocalAddr() returning IPV6 address - java

I have some code to determine whether a web request has been made from the local machine. It uses HttpServletRequest.getLocalAddr() and compares the result to 127.0.0.1.
However, in the last day this has started failing for requests made from a Chrome browser. The address is now in IPV6 format rather than IPV4, i.e. 0:0:0:0:0:0:0:1. If IE is used rather than Chrome the address is still IPV4.
What would cause this? Is it something to do with Chrome, maybe an update to the browser? Or is it more likely to be my environment?

You cannot rely on HttpServletRequest.getLocalAddr() to always return IPv4 address. Instead, you should either be checking if that address is an IPv4 or IPv6 address and act accordingly
InetAddress inetAddress = InetAddress.getByName(request.getRemoteAddr());
if (inetAddress instanceof Inet6Address) {
// handle IPv6
} else {
// handle IPv4
}
or resolve "localhost" to all possible addresses and match the remote address against that
Set<String> localhostAddresses = new HashSet<String>();
localhostAddresses.add(InetAddress.getLocalHost().getHostAddress());
for (InetAddress address : InetAddress.getAllByName("localhost")) {
localhostAddresses.add(address.getHostAddress());
}
if (localhostAddresses.contains(request.getRemoteAddr())) {
// handle localhost
} else {
// handle non-localhost
}
See this useful post.

Related

Make Java report a IPv6 address insted of IPv4

For a project in Java, i use a users ip address as a unique identifier for a website. It all works fine when a user only has a IPv4 address.
But here's my problem, when a user has a IPv6 address, Java will report a IPv4 address, while their browser will report a IPv6 address (In the $_SERVER['REMOTE_ADDR'] call in PHP).
So how do i make Java report it's IPv6 address insted of IPv4 ?
Edit: Some clarification:
This is only used to allow one person to download a file. It does not matter if several people use the same PC, not really important.
Say a user goes to http://whatismyipaddress.com/ with chrome, it will display a IPv6 address.
But if i now use Java to fetch http://whatismyipaddress.com/ it will show a IPv4 address. Why is this and how can i make it show the IPv6 address shown in Chrome ?
Edit 2: The code i use
public static String get(String url) throws WebFetchException {
String result = "";
try {
URL url1 = new URL(url);
HttpsURLConnection urlConn = (HttpsURLConnection) url1.openConnection();
urlConn.setConnectTimeout(8 * 1000);
urlConn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String text;
while ((text = in.readLine()) != null) {
result = result + text;
}
in.close();
}
} catch (Exception e) {
throw new WebFetchException("There was an exception while fetching the requested page: " + url);
}
return result;
}
The assumption that an ip address can be used as an identifier is wrong. More and more ISPs are deploying some form of NAT so many users will share a pool of IPv4 assesses. The address that a user is coming from can change from one connection to the other, so you can't rely on it being stable.
On the other hand more users also get IPv6, and devices have multiple IPv6 addresses that will change over time.
It also happens that because of connectivity issues users will switch between IPv4 and IPv6. Well, the user won't even notice, their device will just do it.
So relying on ip addresses just won't work.

InetAddress.getByName returning wrong IP address

I have been using the following code on a server.
public SocketServer(int port,String inetAddress) throws IOException {
this.port = port;
this.ia = InetAddress.getByName(inetAddress);
log.info(String.format("Internet Address %s using port %d for provided IP Address %s", this.ia.toString() ,this.port ,inetAddress.toString()));
s = new ServerSocket(port,50,this.ia );
}
This works fine on my local server but on production it is providing wrong address.
Production server do contain following type of IPs:-
Private IP
VPN IP
Public IP
I am providing private IP and expecting the server to connect using that private IP but instead it is connecting using the VPN IP.
One more thing i though to do was to use InetAddress.getByAddress() but i am unable to convert my IP in string to a byte array.
Can anyone suggest me any solution in this regard?
If I am not mistaken this might be a problem related to DNS. InetAddress.getByName(String host) will return the first IP address assigned to a certain domain name.
I.e. if in your /etc/hosts file you have something like this
192.168.1.1 sandbox1
192.168.1.2 sandbox1
The code
InetAddress.getByName("sandbox1")
will always give you 192.168.1.1
Hope this helps!

why ip address differs when wireless is off?

public class Main {
public static void main(String[] args) throws IOException {
InetAddress myIp = null;
try {
myIp = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
System.out.println("Exception cought.");
System.exit(0);
}
System.out.println(myIp);
}
}
I have this simple question that why my ip address is different when my wireless is off?
it's still the same computer, so why does it change? (isn't this a unique number?)
The IP address of the computer depends on the network it's connected to (and indeed, the same machine may have more than one, if it has multiple adapers).
So if I connect my machine to one of my networks, it may have the address 192.168.10.7 whereas on another of my networks, it may be 192.168.17.12. It can vary between connections as well, although in practice they tend to be a bit sticky. (It depends on how the DHCP server is configured.)
Your adapter can be configured with a fixed address, but if you do that, it has to be an address the network it's connecting to has reserved for it. Otherwise it may not work at all ("No route to host") or may conflict with another machine using the network.
.An IP address is the address of a network adapter within a specific local network.
It will be different when connected to different networks.
When not connected to any network, it will either be a link-local address or an auto-configuration address.
You might want the MAC address, which is the hardware address of a single network adapter and is not very likely to change.
The provided code returns HOSTNAME/IP-Address(xx.xx.xx.xx).
Hostname is your computer name ex: MY-PC and then you get the IP corresponding to it.
When you are connected to a network, InetAddress.getLocalHost() asks the DHCP server in the network "what is the address of MY-PC (the name of your computer)", the DHCP replies -> 33.44.55.66
Try the following CMD commands when both connected and disconnected.
\>hostname
MY-PC
\>nslookup MY-PC
44.55.66.77
When you are not connected to a network there are two possibilities:
You do not get a hostname (default is localhost)
You do get a hostname, but there is no DHCP server on the network to return an IPaddress,
so you get loopback - 127.0.0.1
If you want to "call" your computer on the network locally, use the loopback http://www.pcmag.com/encyclopedia/term/57812/loopback-address
Hope this helps
No. You're confusing IP and MAC addresses. The MAC address is a serial number of hardware(but may be programatically changed on certain chipsets).
The IP address is either software-determined or determined by the network. It can differ between networks or even with time.
IP addresses are (usually) interface specific, not machine specific.
If your machine only has one interface the difference is moot, but it matters if (for example) you have both wired and wireless ethernet.
Also note that if you do have both and attempt to use them both at the same time on the same subnet that things will likely get very confused!

Error 0:0:0:0:0:0:0:1%0 getting IP V6 client

I have this function to get the HostAddress from my request (HttpServletRequest) on Java. But using Jetty 7.x and my IP is ipV6 I have always this error with iPv6 address.
My function:
xxxx.getIP(request, false);
public static String getIP(HttpServletRequest request, boolean proxy) {
String ip = "";
log.debug("X-getHeaderNames ["+ request.getHeaderNames()+"]");
if (proxy) {
ip = XFordwardedInetAddressUtil.getAddressFromRequest(request);
} else {
String _ip = request.getRemoteAddr();
ip = InetAddresses.forString(_ip).getHostAddress();
}
return ip;
}
The error:
DEBUG: org.encuestame.core.exception.EnMeMappingExceptionResolver - Resolving exception from handler [org.encuestame.mvc.controller.TweetPollController#4fc23996]: java.lang.IllegalArgumentException: '0:0:0:0:0:0:0:1%0' is not an IP string literal.
java.lang.IllegalArgumentException: '0:0:0:0:0:0:0:1%0' is not an IP string literal.
at org.encuestame.utils.net.InetAddresses.forString(InetAddresses.java:59)
at org.encuestame.core.util.EnMeUtils.getIP(EnMeUtils.java:210)
at org.encuestame.mvc.controller.AbstractBaseOperations.getIpClient(AbstractBaseOperations.java:262)
at org.encuestame.mvc.controller.TweetPollController.detailTweetPollController(TweetPollController.java:332)
at org.encuestame.mvc.controller.TweetPollController$$FastClassByCGLIB$$6990b004.invoke()
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedIntercepto
I know the iPv6 localhost format should be '0:0:0:0:0:0:0:1' but my request always return this string '0:0:0:0:0:0:0:1%0'
Anyone can help me?
The problem is that the class you're using (org.encuestame.utils.net.InetAddresses) clearly doesn't support IPv6. Try using the java InetAddress class that Joachim mentioned in his answer.
When you're using a link local address, the % should be included in the address.
This is due to the fact that the computer needs to know which interface/zone the request came from to be able to reply out the correct interface.
If you're using correctly configured, Internet routable IPv6 addresses, the zone index will not be a part of the address.
In this case, I can't see a way to solve your problem for localhost/link local testing except to filter out anything after the % sign, or use another class that works with link local addresses to parse the address.
EDIT: Here's another - similar - question I didn't see earlier.

Cannot get hostname from getHostName

I am trying to get hostname/computer name using this method. Unfortunately i only can get localhost but not other computer.
private String getHostName(String _strIP) {
try {
InetAddress inetAddress = InetAddress.getByName(_strIP);
System.out.println("getHostAddress : " + inetAddress.getHostAddress());
System.out.println("getHostName : " + inetAddress.getHostName());
System.out.println("getCanonicalHostName : " + inetAddress.getCanonicalHostName());
return inetAddress.getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return strDefaultHostName;
}
the result (not localhost)
getHostAddress : 192.168.2.139
getHostName : 192.168.2.139
getCanonicalHostName : 192.168.2.139
the result (localhost)
getHostAddress : 127.0.0.1
getHostName : localhost
getCanonicalHostName : localhost
Thank you
We've established roughly what the problem is in tangens' answer.
I think you can fix the problem pretty simply by putting host names into your hosts file.
%SystemRoot%\system32\drivers\etc\hosts
is the file you're looking for; localhost is defined here. You want to put a name and address line in it for every host you want to resolve.
I've never tried this. If it doesn't work, you get your money back.
Update
The above is the "quick hack" solution. This essentially entails that whenever someone manually changes the IP address of a host you're interested in, someone must at the same time change the hosts files on any machines that want to access those hosts.
The other alternative is to operate your own DNS server. You still need to update IP addresses when a host's address changes, but you only need to do so in one place, and you get both forward and reverse name resolution throughout your network. This takes more setting up but is easier to maintain in the long run.
Here is a very useful reference: http://www.dns.net/dnsrd/servers/windows.html
They mention that the "built in" Microsoft DNS server is a terrible solution (up until the one in Windows 2003 Server) but mention at least two alternatives, one commercial and one free. BIND is what is currently holding much of the Internet together, DNS-wise, and it's great that they have a Windows port too.
Looking at the source for InetAddress.getHostName() (Sun JDK8)...
The method performs the following logic:
Loops through the available sun.net.spi.nameservice.NameService's
Performs a reverse DNS lookup - e.g. 192.168.0.23 -> frodo.baggins.com.au
*Checks with the java.lang.SecurityManager, to see if "we have permission to connect" to hostname
*Performs a forward DNS lookup on the hostname, to prevent spoofing - e.g. frodo.baggins.com.au -> 192.168.0.99
If forward lookup result matches the original address (e.g. 192.168.0.23 == 192.168.0.99?), return hostname, otherwise return getHostAddress()
*If step 3 or 4 throws a SecurityException/UnknownHostException, return getHostAddress()
For me, step #2 successfully resolved the hostname, but failed at step #4 with an UnknownHostException.
TLDR; you must fulfill ALL of the following requirements:
the SecurityManager must provide permission to access the host
you must be able to forward AND reverse DNS lookup your InetAddress
the forward lookup details MUST match the reverse lookup details
Only then will Java give you the hostname.
OR, you could bypass these steps with the following method, and just get the hostname.
#SuppressWarnings("unchecked")
public static String getHostName(InetAddress addr) {
String host = null;
List<NameService> nameServicesImpl = new ArrayList<>();
try {
// do naughty things...
Field nameServices = InetAddress.class.getDeclaredField("nameServices");
nameServices.setAccessible(true);
nameServicesImpl = (List<NameService>) nameServices.get(null);
} catch (Throwable t) {
throw new RuntimeException("Got caught doing naughty things.", t);
}
for (NameService nameService : nameServicesImpl) {
try {
// lookup the hostname...
host = nameService.getHostByAddr(addr.getAddress());
} catch (Throwable t) {
// NOOP: problem getting hostname from this name service, continue looping...
}
}
return host != null ? host : addr.getHostAddress();
}
Your DNS is broken. Then IP-numbers are returned instead.
The javadoc of InetAddress.getCanonicalHostName() says:
Gets the fully qualified domain name for this IP address. Best effort method, meaning we may not be able to return the FQDN depending on the underlying system configuration.
If there is a security manager, this method first calls its checkConnect method with the hostname and -1 as its arguments to see if the calling code is allowed to know the hostname for this IP address, i.e., to connect to the host. If the operation is not allowed, it will return the textual representation of the IP address.
I looks like your system configuration isn't correct. Are you running from within an applet?
Reply Feedback for Carl Smotricz
Great answer, but we still don't know if the host name has been updated or not...
This is something like we hardcode.
Anyway thank you so much
# Copyright (c) 1993-1999 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
127.0.0.1 localhost
192.168.2.139 dev-testing
The problem can be caused by multiple reasons.
Reason 1: the IP address doesn't have a hostname
This is probably the most common reason, and has nothing to do with security managers.
If an IP address doesn't resolve to a hostname, because there is no hostname, then you would expect getHostName() to return null or throw a UnknownHostException, but this doesn't happen. Instead getHostName() simply returns the IP address as a string back again. For reasons unknown to me, this common situation is undocumented.
So if the IP address is the same as the result returned by getHostName(), then the hostname doesn't exist.
Detailed explanation
The following JDK code is the cause of this undocumented problem:
https://github.com/openjdk/jdk/blob/jdk-17+35/src/java.base/share/classes/java/net/InetAddress.java#L697
public class InetAddress implements java.io.Serializable {
private static String getHostFromNameService(InetAddress addr, boolean check) {
String host = null;
try {
// first lookup the hostname
host = nameService.getHostByAddr(addr.getAddress());
/* check to see if calling code is allowed to know
* the hostname for this IP address, ie, connect to the host
*/
if (check) {
#SuppressWarnings("removal")
SecurityManager sec = System.getSecurityManager();
if (sec != null) {
sec.checkConnect(host, -1);
}
}
/* now get all the IP addresses for this hostname,
* and make sure one of them matches the original IP
* address. We do this to try and prevent spoofing.
*/
InetAddress[] arr = InetAddress.getAllByName0(host, check);
boolean ok = false;
if(arr != null) {
for(int i = 0; !ok && i < arr.length; i++) {
ok = addr.equals(arr[i]);
}
}
//XXX: if it looks a spoof just return the address?
if (!ok) {
host = addr.getHostAddress();
return host;
}
} catch (SecurityException e) {
host = addr.getHostAddress();
} catch (UnknownHostException e) {
host = addr.getHostAddress();
// let next provider resolve the hostname
}
return host;
}
}
So what happens is that the IP-address is passed to NameService.getHostByAddr() (NameService is a private interface), which has this (private) documentation in the source code:
Lookup the host corresponding to the IP address provided
#param addr byte array representing an IP address
#return {#code String} representing the host name mapping
#throws UnknownHostException if no host found for the specified IP address
So NameService.getHostByAddr() throws an UnknownHostException if the IP doesn't have a hostname, but InetAddress.getHostFromNameService() swallows this exception and instead, it returns the provided IP-address itself!!! IMO it should have let the exception be thrown instead of swallowing it, because swallowing it makes it more difficult for the client to determine whether a hostname exists.
You can check if the IP address has a hostname by using the nslookup commandline tool: nslookup 192.168.2.139. If it returns something like:
** server can't find 139.2.168.192.in-addr.arpa: NXDOMAIN (Linux) or *** can't find 192.168.2.139: Non-existent domain (Windows) then there is no hostname.
Reason 2: a security manager is applied
By default, Java doesn't have a security manager enabled. In that case, this reason doesn't apply.
A security manager is an object that defines a security policy for an application. If you have a security manager and want to find out if it is the cause of your problem, then you should check whether it is allowing you to open a socket to the resolved hostname (if any). To do so, first use nslookup 192.168.2.139 and verify if a hostname is resolved. If no hostname is resolved, then your problem is caused by "Reason 1". If it does resolve to a hostname, for example myhostname, then try this:
SecurityManager sec = System.getSecurityManager();
if (sec != null) {
sec.checkConnect("myhostname", -1);
}
If checkConnect() throws a SecurityException, then a SecurityManager is active and is causing the problem. So then you could look into how you can configure your securityManager to solve the problem.

Categories