Yash Mehta
Yash Mehta

Reputation: 3

Remote PC name and IP using Java

I am trying to get the remote PC names and IP address connected in the network using Java. I am able to get the IP's but can't get the names of the devices. I am attaching the code for reference.

Java Code:

import java.io.IOException;
import java.net.InetAddress;

public class findIP {


    public static void main(String[] args) throws IOException {

        InetAddress localhost = InetAddress.getLocalHost();
        // this code assumes IPv4 is used
        byte[] ip = localhost.getAddress();
        String N = localhost.getHostName();

        for (int i = 1; i <= 254; i++)
        {
            ip[3] = (byte)i;
            InetAddress address = InetAddress.getByAddress(ip);
            InetAddress name = InetAddress.getByName(N);
        if (address.isReachable(1000))
        {
            System.out.println(address+"            " +"Device Name: "+name);
        }

Upvotes: 0

Views: 1719

Answers (3)

Timir
Timir

Reputation: 1425

First, InetAddress.getByName(N) is attempting to resolve your server hostname, not client. So your code should reflect your intent as :

String name = address.getHostName();

Now to answer your question, InetAddress.getHostName() will return the result of reverse DNS lookup for the corresponding IP address. Not all clients of your application will have a DNS record, so you may not see a "device name" anyway.

Upvotes: 2

Sheetal Mohan Sharma
Sheetal Mohan Sharma

Reputation: 2924

This should do

 InetAddress host = InetAddress.getByName("xxx.xxx.xxx.xxx");
 System.out.println(host.getHostName());

Upvotes: 1

VHS
VHS

Reputation: 10184

Replace

InetAddress name = InetAddress.getByName(N);

with

String hostName = address.getHostName();.

What you get by calling getByName is the IP address, not the host name. Read the docs.

Upvotes: 1

Related Questions