How to Get Subnet Mask of Local System Using Java

Get all IP addresses from a given IP address and subnet mask

Answering my own question, solution is to use Apache commons.net library

import org.apache.commons.net.util.*;

SubnetUtils utils = new SubnetUtils("192.168.1.0/24");
String[] allIps = utils.getInfo().getAllAddresses();
//appIps will contain all the ip address in the subnet

Read more: Class SubnetUtils.SubnetInfo

Get all the Up ip in the local network -java

I tried this program to find all the up ip in the subnet of the system connected.

package com.Server;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class Subnet
{
public void Subnet() throws UnknownHostException, SocketException
{
Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration ee = n.getInetAddresses();
while (ee.hasMoreElements())
{
InetAddress i = (InetAddress) ee.nextElement();
String ip = i.getHostAddress();

String sip = ip.substring(0, ip.indexOf('.',ip.indexOf('.',ip.indexOf('.')+1) + 1) + 1);
try {
for(int it=1;it<=255;it++)
{
String ipToTest = sip+it;
boolean online = InetAddress.getByName(itToTest).isReachable(100);
if (online) {
System.out.println(ipToTest+" is online");
}

}
} catch (IOException e1) {
System.out.println(sip);
}
}
}
}
}

How to check if an IP address is from a particular network/netmask in Java?

Apache Commons Net has org.apache.commons.net.util.SubnetUtils that appears to satisfy your needs. It looks like you do something like this:

SubnetInfo subnet = (new SubnetUtils("10.10.10.0", "255.255.255.128")).getInfo();
boolean test = subnet.isInRange("10.10.10.10");

Note, as carson points out, that Apache Commons Net has a bug that prevents it from giving the correct answer in some cases. Carson suggests using the SVN version to avoid this bug.



Related Topics



Leave a reply



Submit