// NOTE! This code contains minor bits taken from Sun's JDK 1.1.7 sources, // in particular java.lang.Integer and java.net.InetAddress. import edu.mit.media.hive.support.Debug; import java.net.UnknownHostException; /** Simple data structure to store host info. **/ public class Host { public int ipAddress; public Host(String s) throws UnknownHostException { ipAddress = quadToInt(s); } public String toString() { return this.intToQuad(ipAddress); } // taken from JDK 117 java.lang.Integer public boolean equals(Object obj) { if ((obj != null) && (obj instanceof Host)) { return ipAddress == ((Host)obj).ipAddress; } return false; } public int hashCode() { return ipAddress; } public static int quadToInt(String host) throws UnknownHostException { // this code taken from JDK 117 sources for java.net.InetAddress int IP = 0x00; int hitDots = 0; char[] data = host.toCharArray(); for(int i = 0; i < data.length; i++) { // loop over dots char c = data[i]; if (c < 48 || c > 57) { // !digit throw new UnknownHostException(host); } int b = 0x00; while(c != '.') { // grab all numbers to . if (c < 48 || c > 57) { // !digit throw new UnknownHostException(host); } b = b*10 + c - '0'; if (++i >= data.length) break; c = data[i]; } if(b > 0xFF) { /* bogus - bigger than a byte */ throw new UnknownHostException(host); } IP = (IP << 8) + b; hitDots++; } if(hitDots != 4 || host.endsWith(".")) { throw new UnknownHostException(host); } return IP; } public static String intToQuad(int n) { // This code taken from java.net.InetAddress. return ((n >>> 24) & 0xFF) + "." + ((n >>> 16) & 0xFF) + "." + ((n >>> 8) & 0xFF) + "." + ((n >>> 0) & 0xFF); } public static void main(String args[]) { int n; try { n = Host.quadToInt(args[0]); String s = Host.intToQuad(n); if (!s.equals(args[0])) System.out.println("Couldn't parse " + args[0]); System.out.println("Parsed: " + new Host(args[0])); } catch (UnknownHostException ex) { Debug.error(ex); } } }