如何使用java获取网络上的所有IP地址?

时间:2014-05-05 05:04:31

标签: java network-programming

我正在使用 InetAddress 类来获取网络上的IP地址。

问题是有时我无法获得某些地址,有时 InetAddress 无法从网络中获取单个IP。

可能是什么问题? 谢谢

我试过下面的代码:

public void fatchAllNetworkIP() throws UnknownHostException, IOException
{
    System.out.println("Fetching IP...");

    InetAddress localhost = InetAddress.getLocalHost();
    byte[] ip = localhost.getAddress();

    for (int i = 1; i <= 254; i++)
    {
        ip[3] = (byte)i;
        InetAddress address = InetAddress.getByAddress(ip);

        if(address.isReachable(1000))
        {
            //JOptionPane.showMessageDialog(null, address);
            System.out.println("IP Address "+i+"is "+address);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

尝试java.net.NetworkInterface,获取所有可用的NetworkInterfaces,然后获取所有附加的InetAddresses

答案 1 :(得分:1)

尝试使用此示例获取192.168.x.x,

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

        byte[] ip = {(byte)192, (byte)168, 0, 0}; //Note: for 192.168.0.x addresses  
        for (int i = 1; i <= 254; i++)  
        {  
            ip[3] = (byte) i;  
            InetAddress address = InetAddress.getByAddress(ip);  
            System.out.printf("InetAddress1: %s\n", address);
        } 


    }

答案 2 :(得分:0)

您需要更改超时,以便系统可以检查是否有来自网络机器的回复..

if(address.isReachable(2000)) {
    System.out.println("IP Address "+i+"is "+address);
}

如果再次出现同样的问题,请尝试增加超时..