[英]How to fetch all IP addresses on network using java?
I am using InetAddress class for fetching IP address on my network. 我正在使用InetAddress类来获取网络上的IP地址。
The problem is that sometime I can not get some addresses and sometime the InetAddress not able to fetch single IP from network. 问题是,有时我无法获取某些地址,有时InetAddress无法从网络中获取单个IP。
What can be the problem? 可能是什么问题? Thanks
谢谢
I have tried below code: 我试过下面的代码:
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);
}
}
}
尝试java.net.NetworkInterface
,获取所有可用的NetworkInterfaces,然后获取所有附加的InetAddresses
Try with this example for 192.168.xx, 试试这个例子192.168.xx,
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);
}
}
You need to change the timeout so that system can check if there is reply from network machine.. 您需要更改超时,以便系统可以检查是否有来自网络机器的回复。
if(address.isReachable(2000)) {
System.out.println("IP Address "+i+"is "+address);
}
if same problem will occur again then try increasing the timeout.. 如果再次出现同样的问题,请尝试增加超时时间..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.