Encoding ipv4 Address for use in Java - java

I'm using PMD to check java code, and I've run into the problem that states, "Do not hard code IPv4 or IPv6 addresses, even 127.0.0.1!" The IPv4 address I'm using is in fact just 127.0.0.1, and is only for testing purposes, but nonetheless I must convert the hard-coded version to some sort of encrypted version. I'm not sure what would be the easiest way to do this.
Any help would be greatly appreciated!

You are not trying to encrypt anything.
What you wan to do is pass in a host name and do the proper host lookup to get the Internet address. Look at the standard JDK's InetAddress and the getAllByName(String host) and getByName(String host)

I've resolved this PMD´s warning in this way:
// Old code
`if (!"127.0.0.1".equals(serverIP)) { ... }`
// New code
`if (!InetAddress.getLoopbackAddress().getHostAddress().equals(serverIP)) { ... }`

Related

Skip DNS lookup in Java

For an app I'm writing I want to completely avoid DNS host name resolution: I'm using numeric IPv4 and IPv6 addresses and I have no use for lookups. I've googled a bit but I can't find a class that allows me to open a connection without causing a DNS request to occur. Any hints?
TIA
If you invoke InetAddress.getByName() with a name that's not really a name, but is an IP address, Java won't perform the DNS lookup.
Another option is to use InetAddress.getByAddress() like so:
byte[] numericAddress = new byte[]{127,0,0,1};
InetAddress.getByAddress(numericAddress); //Will return an InetAddress that points to 127.0.0.1

Inet6Address.getByName() does return (existing) IPv6 but only IPv4 address?

The following always prints the first returned IPv4 address and not the first IPv6 address
although I explicitly used Inet6Adress and not InetAddress. Is this a bug in the OpenJDK 1.7.0 I use?
InetAddress ipv6 = Inet6Address.getByName("www.google.com");
How am I supposed to get one IPv6 adresse for a given host name (or NULL if none exists)?
I do not want to change the resolver preference between IPv4 and IPv6, in this case I really want to see if at least one IPv6 address exists.
It's probably doable by iterating all results of InetAddress.getAllByName() and check for any "instanceof Inet6Address" but that does not look like the supposed way to do it.
Just found this answer .
I am copying textually the answer of the user Pr0gr4mm3r
java.net.Inet6Address does not override getByName()
so it will always return the specific IPv4-Address,
unless your parameter itself is in the form of an valid IPv6-Address, in this case this method will return an Inet6Address-Object.
For example:
getByName("stackoverflow.com") --> Inet4Address
getByName("2001:0db8:85a3:08d3:1319:8a2e:0370:7344") --> Inet6Address

How to get client's IP in NanoHTTPD (HTTP server)?

I'm programming a simple web browser depending on NanoHTTPD project and it's required to get number of visitors using the IP address.
Are there any ways to get the client IP using NanoHTTPD?
In NanoHTTPD.java, find the private class HTTPSession object.
Inside this is public void run(). Find the following line and add the second line after it.
decodeHeader(hin, pre, parms, header);
header.put("IPAddress", mySocket.getInetAddress().getHostAddress());
Now inside your serve function, you can just reference the IPAddress header to get the client's ip address.
I know the answer is probably too late to help you, but hopefully it'll help others searching for the same thing.
I found in the latest master branch, you can get the client ip address by header "http-client-ip" in the IHTTPSession session object.

isReachable in Java doesn't appear to be working quite the way it's supposed to

I'm using Clojure, but I can read Java, so this isn't a Clojure specific question. This doesn't even seem to be working from Java.
I'm trying to implement a bit of a 'ping' function using isReachable. The code I'm using is this:
(.isReachable (java.net.InetAddress/getByName "www.microsoft.com") 5000)
Translated to Java by a good friend of mine:
public class NetTest {
public static void main (String[] args) throws Exception{
String host = "acidrayne.net";
InetAddress a = InetAddress.getByName(host);
System.out.println(a.isReachable(10000));
}
}
Both of these return false. I suppose I must be doin' it wrong, but Google research is telling me differently. I'm confuzzled!
Updated in response to comment that this is wrong:
Using Unix/Linux??
http://bordet.blogspot.com/2006/07/icmp-and-inetaddressisreachable.html says:
Linux/Unix, instead, supports an ICMP "ping" system call. So the implementation of java.net.InetAddress.isReachable() first tries to perform the "ping" system call**; if this fails, it falls back trying to open a TCP socket on [sic - to] port 7, as in Windows.
It turns out that in Linux/Unix the ping system call requires root privileges, so most of the times java.net.InetAddress.isReachable() will fail, because many Java programs are not run as root, and because the target address unlikely has the echo service up and running. Too bad.
The comment below from #EJP indicates the part of about the echo service is wrong, wrong wrong:
That's not correct. isReachable returns true if it gets a ConnectException trying to connect to port 7, as that proves that the host is up and able to send RST segments.
In cases like these, I use a packet sniffer like WireShark, tcpdump (WinDump on Windows) or snoop (Solaris) to confirm what is really happening on the wire.
The correct answer is not actually correct I think. Microsoft.com simply ignore ICMP requests, probably to avoid basic ping flood attacks. As for the second host I've no idea what the problem with the ping might be, but I'm using GNU/Linux and isReachable works just fine.

IP Address not obtained in java

This code used to return my local ip address as 192.xxx.x.xxx but now it is returning 127.0.0.1 . Please help me why the same code is returning different value. Is there something that I need to watch at linux OS.
import java.util.*;
import java.lang.*;
import java.net.*;
public class GetOwnIP
{
public static void main(String args[]) {
try{
InetAddress ownIP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+ownIP.getHostAddress());
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
}
}
127.0.0.1 is the loopback adapter - it's a perfectly correct response to the (somewhat malfomed) question "what is my IP address?"
The problem is that there are multiple correct answers to that question.
EDIT: The docs for getLocalHost say:
If there is a security manager, its
checkConnect method is called with the
local host name and -1 as its
arguments to see if the operation is
allowed. If the operation is not
allowed, an InetAddress representing
the loopback address is returned.
Is it possible that the change in behaviour is due to a change in permissions?
EDIT: I believe that NetworkInterface.getNetworkInterfaces is what you need to enumerate all the possibilities. Here's an example which doesn't show virtual addresses, but works for "main" interfaces:
import java.net.*;
import java.util.*;
public class Test
{
public static void main(String[] args)
throws Exception // Just for simplicity
{
for (Enumeration<NetworkInterface> ifaces =
NetworkInterface.getNetworkInterfaces();
ifaces.hasMoreElements(); )
{
NetworkInterface iface = ifaces.nextElement();
System.out.println(iface.getName() + ":");
for (Enumeration<InetAddress> addresses =
iface.getInetAddresses();
addresses.hasMoreElements(); )
{
InetAddress address = addresses.nextElement();
System.out.println(" " + address);
}
}
}
}
(I'd forgotten just how awful the Enumeration<T> type is to work with directly!)
Here are the results on my laptop right now:
lo:
/127.0.0.1
eth0:
/169.254.148.66
eth1:
eth2:
ppp0:
/10.54.251.111
(I don't think that's giving away any hugely sensitive information :)
If you know which network interface you want to use, call NetworkInterface.getByName(...) and then look at the addresses for that interface (as shown in the code above).
When you use InetAddress.getLocalHost() you are not guaranteed to get a particular interface, ie. you could receive the loopback (127) interface or a connected one.
In order to ensure you always get an external interface, you should use the java.net.NetworkInterface class. The static getByName(String) class will give you the interface with the defined name (such as "eth0"). Then you can use the getInetAddresses() function to obtain the IP addresses (could be just one) bound to that interface.
NetworkInterface ni = NetworkInterface.getByName("eth1");
ni.getInetAddresses();
Check your /etc/host file. If you put 127.0.0.1 first, it will return this as result.
The correct way to get the ip address is to use NetworkInterface.getNetworkInterfaces() and run getInetAddresses() on each of them.
You can use the NetworkInterface.getNetworkInterfaces() method to retrieve an Enumeration of all of the network interfaces for your system.
For each of the NetworkInterface instances, you can then use the getInetAddresses() method to retrieve an Enumeration of all of the InetAddress instances associated with the network interface.
Finally, you can use the getHostAddress() method on each InetAddress instance to retrieve the IP address in textual form.
This is because you have a line in /etc/hosts like
127.0.0.1 localhost
you need to have
192.xxx.xxx.xxx localhost
Though please note that this would be very bad as to solve a code issue you should not modify linux config files. Not only is it not right (and risks breaking some other network aware apps on your linux box) it will also not work anywhere else (unless the admins of those boxes are also like minded).
javadoc for InetAddress.getLocalHost(); read "....an InetAddress representing the loopback address is returned." so it appears that the implementation of getLocalHost() is incorrect
on your UNIX and WIN boxes. The loopback address is nearly allways 127.0.0.1
Found this comment
"A host may have several IP addresses and other hosts may have to use different addresses to reach it. E.g. hosts on the intranet may have to use 192.168.0.100, but external machines may have to use 65.123.66.124. If you have a socket connection to another host you can call
Socket.getLocalAddress() to find out which local address is used for the socket."

Categories