我是
java的新手,我正试图找到一种通过用户输入IP地址范围递增的方法.
例如,从192.168.0.1到192.168.0.255.然而,我的应用程序目前的工作方式是将from和to ip地址作为String.
希望这是有道理的,请不要激怒我,我已经找到了答案!
编辑!
它实际上是ping通过地址范围所以,这里是一个小代码到目前为止,’host’是从另一个类传入的,我想循环遍历地址:
public static String stringPing(String stringPing,String host){ String ipAddress; ipAddress = host; try { InetAddress inet = InetAddress.getByName(ipAddress); boolean status = inet.isReachable(2000); if (status) { stringPing = "\n" +host +" is reachable"; return stringPing; } else { stringPing = "\n" +host +" is unreachable"; return stringPing; } } catch (UnknownHostException e) { System.err.println("Host does not exists"); } catch (IOException e) { System.err.println("Error in reaching the Host"); } return stringPing; }
解决方法
保持地址应该是 – 作为32位整数,并以此形式递增.仅在需要时将其从或转换为String.示例如下.我的IPAddress类完整且功能齐全.
class IPAddress { private final int value; public IPAddress(int value) { this.value = value; } public IPAddress(String stringValue) { String[] parts = stringValue.split("\\."); if( parts.length != 4 ) { throw new IllegalArgumentException(); } value = (Integer.parseInt(parts[0],10) << (8*3)) & 0xFF000000 | (Integer.parseInt(parts[1],10) << (8*2)) & 0x00FF0000 | (Integer.parseInt(parts[2],10) << (8*1)) & 0x0000FF00 | (Integer.parseInt(parts[3],10) << (8*0)) & 0x000000FF; } public int getOctet(int i) { if( i<0 || i>=4 ) throw new IndexOutOfBoundsException(); return (value >> (i*8)) & 0x000000FF; } public String toString() { StringBuilder sb = new StringBuilder(); for(int i=3; i>=0; --i) { sb.append(getOctet(i)); if( i!= 0) sb.append("."); } return sb.toString(); } @Override public boolean equals(Object obj) { if( obj instanceof IPAddress ) { return value==((IPAddress)obj).value; } return false; } @Override public int hashCode() { return value; } public int getValue() { return value; } public IPAddress next() { return new IPAddress(value+1); } } public class App13792784 { /** * @param args */ public static void main(String[] args) { IPAddress ip1 = new IPAddress("192.168.0.1"); System.out.println("ip1 = " + ip1); IPAddress ip2 = new IPAddress("192.168.0.255"); System.out.println("ip2 = " + ip2); System.out.println("Looping:"); do { ip1 = ip1.next(); System.out.println(ip1); } while(!ip1.equals(ip2)); } }