4

我正在寻找一种更好的方法来使用 Java 在我的 LAN 网络中获取计算机名称。我努力了:

byte[] ip = {(byte)192,(byte)168,(byte)178,(byte)1};
    for(int i=1;i<255;i++)
    {
        ip[3] = (byte)i;
        try
        {
            InetAddress addr = InetAddress.getByAddress(ip);
            String s = addr.getHostName();
            System.out.println(s);
        }
        catch(UnknownHostException e)
        {
            System.out.println(e.getMessage());
        }
    }

……但是太慢了。还有其他方法吗?

我在 Windows 上。

任何想法表示赞赏。

4

2 回答 2

8

您可以通过使用多个线程来提高速度。

让每个线程执行一个或多个“try”块的迭代。

于 2013-07-31T19:07:24.387 回答
2

对于那些想知道的人,这就是我想出的:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class nameLookup implements Runnable
{
    byte[] ip;
    String[] names;
    int index;
    public nameLookup(byte[] ip,int index,String[] names)
    {
        this.ip = ip;
        this.names = names;
        this.index = index;
    }
    public void run()
    {
        try
        {
            InetAddress addr = InetAddress.getByAddress(ip);
            names[index]= addr.getHostName();

        }
        catch(UnknownHostException e)
        {
            System.out.println(e.getMessage());
        }
    }
    public static String[] lookUp()
    {
        byte[] ip = {(byte)192,(byte)168,(byte)178,(byte)1};
        String[] names = new String[254];
        Thread threads[] = new Thread[254];

        for(int i=0;i<254;i++)
        {
            ip[3] = (byte)(i+1);
            threads[i] = new Thread(new nameLookup(ip,i,names));
            threads[i].start();
        }
        for(int i=0;i<254;i++)
        {
            try
            {
                threads[i].join();
            }
            catch (InterruptedException e) {
                System.out.print(e.getMessage());
            }

        }
        return names;
    }
}

我仍然希望它更快,但现在至少可以接受。

于 2013-08-01T16:24:15.373 回答