Get name of computer from ipaddress - java

I am trying to get the name of computer from its local IP. This is what I've done so far, but nothing works it just returns the IP address as hostname
InetAddress addr = null;
String hostIP = "192.168.100.10";
try {
addr = InetAddress.getByName(hostIP);
} catch (UnknownHostException e) {
System.out.println("Host " + hostIP + " not found!");
}
String host = addr.getHostAddress();
String hostname= addr.getHostName();
String hostname2 = addr.getCanonicalHostName();
I am expecting to get DESKTOP-DWASDFW as hostname but instead i get 192.168.100.10
UPDATE:
I managed to "fix" it by adding my computer and its ip address manually into the router configuration
but this isn't what im looking for as it requires manually entering every name and IP address. I want something like this app WakeOnLan, it can scan the whole network and get IP address, MAC address and hostname. This app uses arp requests, i researched a lot about how to accomplish something like that in android but found nothing that worked for me (I'm using android 4.2.2)

Related

In java, what's the difference between InetAddress.getLocalHost() and InetAddress.getByName("127.0.0.1")

I am using Windows 8 with JDK 1.7. My IP address is 192.168.1.108, when I am running:
System.out.println(InetAddress.getLocalHost().equals(InetAddress.getByName("localhost")));
OR
System.out.println(InetAddress.getLocalHost().equals(InetAddress.getByName("127.0.0.1")));
Output - It's all false.
InetAddress.getLocalHost() - Output: 192.168.1.108
InetAddress.getByName("localhost") - Output: 127.0.0.1
Further more, my UDP server is binded on InetAddress.getLocalHost() and it can't receive anything from the client if the client send packets to InetAddress.getByName("localhost"). However, it works well if the client send to InetAddress.getLocalHost(). Port is corrent.
Anyone know the difference? Thanks in advance.
From the JDK documentation for getLocalHost():
Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.
In my GNU/Linux box, my host name is "laptop", which is mapped to an address different than 127.0.0.1 in /etc/hosts. There is an equivalent file in Windows at C:\Windows\System32\drivers\etc\hosts.
By default this hosts file is searched before DNS lookup.
The ad1 gives you your address in your LAN/WAN, it seems
(I mean local/private network IP addresses like e.g.
192.168.0.108 or like 10.3.6.55).
See also:
http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
http://download.java.net/jdk7/archive/b123/docs/api/java/net/InetAddress.html#getLocalHost%28%29
But note that ad2 and ad3 are equal in my example.
import java.net.InetAddress;
public class Test014 {
public static void main(String[] args) throws Exception {
InetAddress ad1 = InetAddress.getLocalHost();
InetAddress ad2 = InetAddress.getByName("localhost");
InetAddress ad3 = InetAddress.getByName("127.0.0.1");
printArr(ad1.getAddress());
printArr(ad2.getAddress());
printArr(ad3.getAddress());
System.out.println(ad1.equals(ad2));
System.out.println(ad1.equals(ad3));
System.out.println(ad2.equals(ad3));
}
static void printArr(byte[] arr){
for (int i=0; i<arr.length; i++){
System.out.print("[" + i + "] = " + arr[i] + "; ");
}
System.out.println();
System.out.println("---------");
}
}
Also, check the API docs about when the equals method returns true and when false.
http://download.java.net/jdk7/archive/b123/docs/api/java/net/InetAddress.html#equals%28java.lang.Object%29

Identify server on Tomcat (HttpServletRequest.getLocalAddr() fails)

With Tomcat setup behind Apache, how can an id (IP address ideally) of the server be easily determined?
The specific situation is that multiple servers are setup behind a load balancer, thus the incoming request host name is non-unique and insufficient to identify a particular server for logging purposes. Using HttpServletRequest.getLocalAddr() is unfortunately returning the same hostname instead of the IP address as would be expected (I am assuming this is related to this very old issue here: https://issues.apache.org/bugzilla/show_bug.cgi?id=46082).
Is there a way to make getLocalAddr() perform as documented, or are other methods required to query the IP address of the server?
On our project, we use JMX to get all the config information.
It takes a few steps, because it is like navigating down the server.xml file
This link has some info: http://oss.wxnet.org/mbeans.html
It is probably overkill if all you want is the IP, but I thought I'd throw it out there.
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> theConnectors = mbeanServer.queryNames(
new ObjectName("Catalina:type=Connector,*"),
null);
if (theConnectors != null)
{
for (ObjectName nextConnectorName : theConnectors)
{
InetAddress theInetAddress = (InetAddress) mbeanServer.getAttribute(
nextConnectorName,
"address");
if (theInetAddress != null)
{
ipAddress = theInetAddress.getHostAddress();
}
if (!StringUtil.isEmpty(ipAddress))
{
// found the IP address
break;
}
}
}
For my situation, the solution was to get the IP address of the server directly instead of attempting to get the local address via HttpServleRequest.
I cached the IP for use in my filter via:
private static final String serverIp;
static {
String addressString = null;
try
{
InetAddress address = InetAddress.getLocalHost();
addressString = address.getHostAddress();
} catch (Exception e)
{
logger.error("Exception while attempting to determine local ip address",e);
}
if (addressString != null) serverIp = addressString;
else serverIp = "unknown";
}
I had a similar issue recently (a few years after the original question) and found this question and answers. The issue in my case was that the ServletRequest#getLocalAddr() implementation was returning the remote address instead of the local address. The issue was caused by a regression in Tomcat v9.0.22. It was fixed in v9.0.23. See the question and answer here:
https://stackoverflow.com/a/57725039/9602527

Suggestion about detecting Private Ip Address with an applet

I'm having some troubles to detect client's private ip that conect to a web application I built.
Take a look at my tests results(In machines that runs windows):
1-In some machines(from different location ,countries..) the applet give me the correct ip but
2-In others I've obtained ip=127.0.0.1 :
What have I tried to solve this?
A- for example: I've stopped the avast program protection(web shield) and the applet start to give me the correct private ip.
B- In others machines I tried "point A" but It didn't work
C- I also edit host file but I didn't work as well
What I need from you is to help me to understand what is happening? where to look in order to resolve this...
Please don't answer saying "Why do you need the private ip? It could change..." ... I know all the machines that are going to connect to my web application so I can configure them.
Part of the source code that my applet use:
private String PrivateIP(boolean flag)
{
String s1 = "unknown";
String s2 = getDocumentBase().getHost();
int i = 80;
if(getDocumentBase().getPort() != -1)
i = getDocumentBase().getPort();
try
{
String s = (new Socket(s2, i)).getLocalAddress().getHostAddress();
if(!s.equals("255.255.255.255"))
s1 = s;
}
catch(SecurityException _ex)
{
s1 = "FORBIDDEN";
}
catch(Exception _ex)
{
s1 = "ERROR";
}
if(flag)
try
{
s1 = (new Socket(s2, i)).getLocalAddress().getHostName();
}
catch(Exception _ex)
{
Stat = "Cannot Lookup this IP";
}
return s1;
}
I'll let you more information:
I've traid this http://www.auditmypc.com/digital-footprint.asp in order to obtain the ip from probably other method but the same result, I've also run http://www.auditmypc.com/firewall-test.asp and obtained in the machines that I couldn't obtained the correct ip a message like "Congratulations you don't have any port to be open" xD...
Thanks in advance!
First of all, there can be more than one IP address available on the client, if there is more than one network interface. Which one is returned by your method depends on which is used for new Socket() to open.
Now, you do not have to open sockets to get the client's IP. What you can do instead is to enumerate them like this:
String host = InetAddress.getLocalHost().getHostName();
InetAddress[] addressArray = InetAddress.getAllByName(host);
String[] ipArray = new String[addressArray.length];
for (int i = 0; i < addressArray.length; i++) {
InetAddress addr = addressArray[i];
ipArray[i] = addr.getHostAddress();
}
return ipArray;
Now the ipArray will hold a list of available IP adresses on client's workstation.

problem with finding the hostname with ip addr using InetAddress class

I have written the two program
1st whois.java to find the ip address of the given hostname
import java.net.*;
import java.io.*;
public class whois{
public static void main(String args[]) throws IOException{
String hostName = args[0];
try{
InetAddress ipaddress = InetAddress.getByName(hostName);
System.out.println("IP address: " + ipaddress.getHostAddress());
}catch(UnknownHostException e){
System.out.println("Could not find IP address for: " + hostName);
}
}
}
and other whois2.java which finds hostname for given ip
import java.net.*;
import java.io.*;
class whois2{
public static void main(String args[]){
try{
String str[] = args[0].split("\\.");
byte btArr[] = new byte[]{(byte)Integer.parseInt(str[0]), (byte)Integer.parseInt(str[1]), (byte)Integer.parseInt(str[2]), (byte)Integer.parseInt(str[3])};
InetAddress ipAddr = InetAddress.getByAddress(btArr);
System.out.println("Host name for this is : " + ipAddr.getHostName());
}catch(UnknownHostException e){
System.out.println("Unable to find the host for ip specified " + args[0]);
}
}
}
and then i ran the program with jdk 1.6 and get following outputs:
$java whois google.com
IP address: 209.85.231.104
$java whois2 209.85.231.104
Host name for this is : maa03s01-in-f104.1e100.net
why the host name is different not google.com?
Thanks in advance
The server responsible, as defined by the DNS lookup, for handling requests to a particular hostname need not have the same hostname as that of the original lookup.
A more typical example would be that requests for foobar.com are handled by a server at an IP, with IP having hostname www.foobar.com.
Note also that the handling server may vary by region.
So I get the same using the linux host tool:
joel#bohr:~$ host google.com
google.com has address 173.194.37.104
... requests to google.com should be handled by the server at 173.194.37.104
joel#bohr:~$ host 173.194.37.104
104.37.194.173.in-addr.arpa domain name pointer lhr14s02-in-f104.1e100.net.
... the hostname of the server at 173.194.37.104 is lhr14s02-in-f104.1e100.net
joel#bohr:~$ host lhr14s02-in-f104.1e100.net
lhr14s02-in-f104.1e100.net has address 173.194.37.104
... and sanity check, the IP of lhr14s02-in-f104.1e100.net is indeed 173.194.37.104
whois(ip) resolves to the name of the registered server, not to an entry on a domain name server.
Same happens when we use whois services on the web:
http://whois.domaintools.com/google.com resolves to IP 74.125.155.99 (from my location!), http://whois.domaintools.com/74.125.155.99 resolves the host px-in-f99.1e100.net (which again is different from your results)

Get Application Server name or ip and port in Java

We would like to identify and display the server and port that a Java application is running on that is behind a proxy web server. This means that getServerName() and getServerPort() return the server name of the proxy and its port (80).
We have two application server instances running on a single physical box and therefore have two active ports per box i.e. 9080, 9081. What I'd like to have is <Application Server Name>:<Application Server Port> displayed.
Any ideas? I'm a complete Java noob, sorry if this is a basic question.
The server hostname is part of the request, as it depends on what URL the client used to reach your host. The value you get in this way is defined on the client and does not have to be what you expect.
If you are interested in the local hostname, you can try:
String hostname = InetAddress.getLocalHost().getHostName();
You can use ServletRequest#getLocalXXX() methods for this.
ServletRequest#getLocalName() returns local hostname.
ServletRequest#getLocalAddr() returns local IP.
ServletRequest#getLocalPort() returns local port.
Crunchify provides a nice example for this.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class CrunchifyGetIPHostname {
public static void main(String[] args) {
InetAddress ip;
String hostname;
try {
ip = InetAddress.getLocalHost();
hostname = ip.getHostName();
System.out.println("Your current IP address : " + ip);
System.out.println("Your current Hostname : " + hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}

Categories

Resources