자바·JSP2015. 10. 20. 13:12

package getIpList;

public class IpConverter {

public static void main(String[] args) {

IpConverter obj = new IpConverter();

String ip1 = "192.168.1.100";

String ip2 = "192.168.2.255";

final long from = obj.ipToLong(ip1);

final long to = obj.ipToLong(ip2);

if(from > to) {

System.out.println("시작IP는 끝IP보다 값이 작아야 합니다.");

return;

}

for (long i = from; i <= to; i++) {

   System.out.println(obj.longToIp(i));

}

}

public long ipToLong(String ipAddress) {

// ipAddressInArray[0] = 192

String[] ipAddressInArray = ipAddress.split("\\.");

long result = 0;

for (int i = 0; i < ipAddressInArray.length; i++) {

int power = 3 - i;

int ip = Integer.parseInt(ipAddressInArray[i]);

// 1. 192 * 256^3

// 2. 168 * 256^2

// 3. 1 * 256^1

// 4. 2 * 256^0

result += ip * Math.pow(256, power);


}

return result;

}

public String longToIp(long i) {

return ((i >> 24) & 0xFF) + 

                   "." + ((i >> 16) & 0xFF) + 

                   "." + ((i >> 8) & 0xFF) + 

                   "." + (i & 0xFF);

}

}

Posted by 미랭군