-2
InetAddress localhost = null;
try {
    localhost = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
    /* Purposely empty */
}

byte[] ip = localhost.getAddress();
int i = 1;
while (i <= 254) {
    ip[3] = (byte) i;
    InetAddress address = null;
    try {
        address = InetAddress.getByAddress(ip);
    } catch (UnknownHostException ex) {
        /* Purposely empty */
    }

    String HostName = address.getHostName();
    if (!address.getHostAddress().equals(address.getHostName())) {
        list.addElement(HostName);
    }
    i++;
}

(I have problem is long the run time. How I can reduce the run time in this code)

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Eman.S
  • 1
  • 1

1 Answers1

0

I had a similar issue involving network lookups for IP Addresses. The issue of network latency is just as "that other guy" said...it's driven by the network. How long and how many hops it takes to get to the destination.

The only solution I found was threading out the lookups, InetAddress.getByAddress(ip) in your case. My solution was to setup an ExecutorService with 10 threads. Package each InetAddress.getByAddress(ip) into a Callable. Monitor the Callable for completion. package another one and start it. Have a look at one of my questions on this forum related to this very issue :

ExecutorService - How to set values in a Runnable/Callable and reuse

Be cautious with the ExecutorService (as I found out). The number of threads really depends on the number of CPUs (Power) of your runtime hardware. Too many threads and it'll grind to halt (trust me on this). Too few threads and your time reduction may not get reached.

I've left the department in my Company where I implemented the final solution, so I don't have the code readily available. But the above link provides some basic code on the ExecutorService and using Callable objects.

Community
  • 1
  • 1
lincolnadym
  • 909
  • 1
  • 12
  • 29