generating IP addresses

jon soons

Greenhorn

Posts: 5

posted 14 years ago

I need to generate all the IPaddresses on the 10.3.0.0 subnet so that I can find where the printers are and query them. When I compile I get an OutofMemoryException. Is there a right way to do this? import java.util.*; class PrinterAddress { Collection c = new Vector();ArrayList getAddrs() { for (byte a=0;a < 0xff;a++) { for (byte b=0;b < 0xff;b++) { byte[] address = new byte[] {10, 3, a, b}; c.add(address); } } return new ArrayList(c); } // For testing purposes only : public static void main(String[] args) { PrinterAddress pa = new PrinterAddress();ArrayList addrarray = pa.getAddrs(); Iterator i = addrarray.iterator(); while (i.hasNext()) { Object o = i.next(); System.out.println(o); } } }

Java bytes are signed, and range from -128 to +127; thus they are always less than 0xff (256). Therfore "a" is always 0 and the innermost loop runs until the program runs out of memory. To patch this up: use "int" counters, and cast to bytes. Furthermore, note that you want your loops to count from 0 to 0xff, so the test should be either "<= 0xff" or better "< 0x100". To do it an altogether better way: why store all the addresses in a collection? Test each one as you generate it, and store only the successful ones in a collection. Uses much less storage!