Thứ Năm, 4 tháng 4, 2013

Using Java to scan a local network for available IP Addresses range.

For a programming language that was built from the start to be network-oriented, Java is fairly light on networking support in its libraries. Often, IP addresses are better treated in their 'real' nature, as numbers, rather than as strings. Here's how to scan (in Java version 5 and above) a range of IP addresses to see which machines are up. The code can be found HERE

import java.net.InetAddress;
public class ScanNet {
    public static void main(String[] args) throws Exception {
        int[] bounds = ScanNet.rangeFromCidr("192.168.1.255/24");        for (int i = bounds[0]; i <= bounds[1]; i++) {
            String address = InetRange.intToIp(i);
            InetAddress ip = InetAddress.getByName(address);

            if (ip.isReachable(100)) { // Try for one tenth of a second
                System.out.printf("Address %s is reachable\n", ip);
            }
        }
    }

    public static int[] rangeFromCidr(String cidrIp) {
        int maskStub = 1 << 31;
        String[] atoms = cidrIp.split("/");
        int mask = Integer.parseInt(atoms[1]);
        System.out.println(mask);

        int[] result = new int[2];
        result[0] = InetRange.ipToInt(atoms[0]) & (maskStub >> (mask - 1)); // lower bound
        result[1] = InetRange.ipToInt(atoms[0]); // upper bound
        System.out.println(InetRange.intToIp(result[0]));
        System.out.println(InetRange.intToIp(result[1]));

        return result;
    }

    static class InetRange {
        public static int ipToInt(String ipAddress) {
            try {
                byte[] bytes = InetAddress.getByName(ipAddress).getAddress();
                int octet1 = (bytes[0] & 0xFF) << 24;
                int octet2 = (bytes[1] & 0xFF) << 16;
                int octet3 = (bytes[2] & 0xFF) << 8;
                int octet4 = bytes[3] & 0xFF;
                int address = octet1 | octet2 | octet3 | octet4;

                return address;
            } catch (Exception e) {
                e.printStackTrace();

                return 0;
            }
        }

        public static String intToIp(int ipAddress) {
            int octet1 = (ipAddress & 0xFF000000) >>> 24;
            int octet2 = (ipAddress & 0xFF0000) >>> 16;
            int octet3 = (ipAddress & 0xFF00) >>> 8;
            int octet4 = ipAddress & 0xFF;

            return new StringBuffer().append(octet1).append('.').append(octet2)
                                     .append('.').append(octet3).append('.')
                                     .append(octet4).toString();
        }
    }
}

0 nhận xét:

Đăng nhận xét