Getting the Host name of a Local IP address (java) - java

I use this method in a loop to get the host name of 4 terminal in my local network identified by the ip address terminal[i].getIp() .
try {
// Get hostname by textual representation of IP address
InetAddress addr = InetAddress.getByName(terminal[i].getIp());
// Get the host name
String hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
the problem here its that code take so long to return the result (up to 5 seconds)
I wonder if there is another more optimized method.

Try the library from Google Guava, I think there are more optimized
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/net/InetAddresses.html

Related

How to check Internet availability in Java using nslookup?

Currently I am using URL()
public boolean isInternetAvailable(){
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
urlConnect.setConnectTimeout(5000);
Object objData = urlConnect.getContent();
return true;
} catch (Exception e) {}
return false;
}
But In the requirement, we don't want to use any URL. We want to ping localhost if connection is available than return true otherwise flase.
For nslookup I am using
try
{
InetAddress inetAddress = InetAddress.getByName("localhost");
System.out.println("Host: " +inetAddress.getHostName());
System.out.println("IP Address: " +inetAddress.getHostAddress());
System.out.println("IP Address: " +inetAddress.isSiteLocalAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
But I am not understand how to check the connection availability with nslookup.
Please suggest best approach for it. Thanks
There are several catches to this question:
Starting with the most specific one - connecting to localhost: even if your computer does not have a network card, it will be able to resolve localhost on a loopback interface and connect to itself (if there is an open port).
Your DNS may be down/misconfigured, so you cannot resolve example.com but you can connect to it by IP (93.184.216.34) - does that mean than "internet is not available"?
The firewall in your company may be blocking certain sites, but allowing other - does that mean than "internet is not available"?
The server of example.com is down while all the other sites in the world work fine. Does that mean than "internet is available" or not?
The firewall in your company may be allowing HTTP connections only on standard ports 80 and 443 and disallowing other. Thus, http://example.com connects, but http://example.com:12345 does not. Does that mean than "internet is available" or not?
So the only question you can actually ask is whether you can connect to a particular host on a particular port using its domain name and/or its IP address.
Figured out a final solution using NetworkInterface:
Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces();
while(eni.hasMoreElements()) {
Enumeration<InetAddress> eia = eni.nextElement().getInetAddresses();
while(eia.hasMoreElements()) {
InetAddress ia = eia.nextElement();
if (!ia.isAnyLocalAddress() && !ia.isLoopbackAddress() && !ia.isSiteLocalAddress()) {
if (!ia.getHostName().equals(ia.getHostAddress()))
return true;
}
}
}
I have got solution from here:- Java Quickly check for network connection

MQTT - validation for incorrect IP and Port

I want to validate that given IP and port are running in MQTT if not then i have to show exception to user. here is my code,
try {
MqttMessage message2 = new MqttMessage();
MQTT mqtt_connect = new MQTT();
mqtt_connect.setHost(Host_Address, port);
String topic = "/call/MQTT_Config";
mqtt_connect.setClientId("MQTT_Config");
mqtt_connect.setWillRetain(false);
mqtt_connect.isWillRetain();
mqtt_connect.setWillTopic(topic);
BlockingConnection m_publisher = mqtt_connect.blockingConnection();
m_publisher.connect();
if(m_publisher.isConnected()){
System.out.println("connected");
m_publisher.disconnect();
}
else
{
System.out.println("not connected");
return "Port or IP may not running";
}
} catch (Exception e) {
e.printStackTrace();
return "failure";
}
when i give correct IP and port then it goes to if(m_publisher.isConnected()) condition fine but when i give wrong IP or port then it comes till m_publisher.connect(); and then there is nothing happen, like loading console only.Is not going to next step. why?
i have to show some validation when user give unmatched IP or MQTT port. where am i doing wrong?
The problem here will depend on what the user enters.
If they enter an IP address for a machine that exists but is not listening on the port then the machine will respond quickly with a connection refused message
If they enter an IP address for a machine that doesn't exist then the code will wait for the TCP timeout (default is 15mins) before raising an error.

What name do i use to connect to a server socket in java

I am writing a telnet like program in java using the server socket and socket classes. This is my current code for the client program. The user types in the server name and the port they would like to connect on.
static Socket getSocket()
{
while(true)
{
System.out.println("What server do you want to connect to on which port?");
String info = sc.nextLine();
String host = info.split(" ")[0];
int port = Integer.parseInt(info.split(" ")[1]);
try
{
InetAddress ip = InetAddress.getByName(host);
return new Socket(ip, port);
}
catch (UnknownHostException e)
{
System.err.println("The host is unknown.");
}
catch (IOException e)
{
System.err.println("Network error.");
}
}
}
I tried connecting on localhost, and it worked. Then i tried connecting with my friend on a remote computer using the ip address as the network name and it did not work giving an exception. What name do i use to connect to a remote server.
You need to give your friend your remote IP address.

How to get the IP address of a system using Android phone?

How to get the IP address of the PC using Android phone? (In particular how to fetch the IP address of a system with a specific MAC address, connected on the same network as the Android phone)?
wired wired
modem--------router---------PC(mac:EE:00:B3:2F:56:12)
|
|
|
wireless
|
|
|
-------------android phone(A)
private String getIP(String mac) {
String ip = null;
try {
BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
String line = "";
while((line = br.readLine()) != null) {
String[] tokens = line.split("\\s+");
// The ARP table has the form:
// IP address HW type Flags HW address Mask Device
// 192.168.178.21 0x1 0x2 00:1a:2b:3c:4d:5e * tiwlan0
if(tokens.length >= 4 && tokens[3].equalsIgnoreCase(mac)) {
ip = tokens[0];
break;
}
}
br.close();
}
catch(Exception e) { Log.e(TAG, e.toString()); }
return ip;
}
But beware: Unless you have already established contact with your PC (and you'll need either its IP address or its name), the ARP table will be empty.
I suppose you'd like to do it the other way round, establish the connection with the PC knowing only its MAC address. Then it's not that simple. You might try to ping everyone on the local network (Runtime.getRuntime().exec("ping -b 192.168.178.255");) just to fill the ARP table.
Or, maybe, you can get the list of all clients with their IP addresses from your router?

Finding mac Address using IP address in java

public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
// InetAddress address = InetAddress.getByName("192.168.46.53");
/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
if (ni != null) {
byte[] mac = ni.getHardwareAddress();
if (mac != null) {
/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
} else {
System.out.println("Address doesn't exist or is not accessible.");
}
} else {
System.out.println("Network Interface for the specified address is not found.");
}
I'm having a problem finding the MAC address of a remote host, but I am able to find the MAC address of my local host. If I have the IP address of the other system can I retrieve the MAC address of that system?
InetAddress address = InetAddress.getByName("192.168.46.53");
if i specify the ip address of a system in my workgroup... ni values gets null.... and not able to fetch it.... but if give my ip address of my system...it fetches???
Thanks,
Sunny
You will only be able to fetch the MAC address of remote hosts on your local LAN, that is, hosts that are in the same subnet as your computer. MAC addresses of hosts more than one hop away (IP hop, not Ethernet hop) cannot be determined.
And note that fetching the corresponding MAC address for hosts on your local LAN requires the permissions necessary to fetch either the ARP table, or those necessary to send and receive raw packets. Most OSes allow reading of the ARP table without special permissions, but the mechanism you use to do so will change depending on the OS. If you need a technique for a particular OS, you will have to update your question to include that info.

Categories