1 4 package com.tc.net; 5 6 import com.tc.exception.TCRuntimeException; 7 import com.tc.util.Assert; 8 9 import java.net.InetAddress ; 10 import java.net.UnknownHostException ; 11 12 19 public class TCSocketAddress { 20 24 private static final byte[] WILDCARD_BYTES = new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0 }; 25 26 29 private static final byte[] LOOPBACK_BYTES = new byte[] { (byte) 127, (byte) 0, (byte) 0, (byte) 1 }; 30 31 34 public static final String LOOPBACK_IP = "127.0.0.1"; 35 36 39 public static final String WILDCARD_IP = "0.0.0.0"; 40 41 44 public static final InetAddress WILDCARD_ADDR; 45 46 49 public static final InetAddress LOOPBACK_ADDR; 50 51 static { 52 try { 53 WILDCARD_ADDR = InetAddress.getByName(WILDCARD_IP); 54 } catch (UnknownHostException e) { 55 throw new TCRuntimeException("Cannot create InetAddress instance for " + WILDCARD_IP); 56 } 57 58 try { 59 LOOPBACK_ADDR = InetAddress.getByName(LOOPBACK_IP); 60 } catch (UnknownHostException e) { 61 throw new TCRuntimeException("Cannot create InetAddress instance for " + LOOPBACK_IP); 62 } 63 } 64 65 public static byte[] getLoopbackBytes() { 66 return (byte[]) LOOPBACK_BYTES.clone(); 67 } 68 69 public static byte[] getWilcardBytes() { 70 return (byte[]) WILDCARD_BYTES.clone(); 71 } 72 73 76 82 public TCSocketAddress(int port) { 83 this(LOOPBACK_ADDR, port); 84 } 85 86 94 public TCSocketAddress(String host, int port) throws UnknownHostException { 95 this(InetAddress.getByName(host), port); 96 } 97 98 106 public TCSocketAddress(InetAddress addr, int port) { 107 if (!isValidPort(port)) { throw new IllegalArgumentException ("port (" + port + ") is out of range (0 - 0xFFFF)"); } 108 109 if (addr == null) { 110 try { 111 addr = InetAddress.getLocalHost(); 112 } catch (UnknownHostException e) { 113 addr = LOOPBACK_ADDR; 114 } 115 } 116 117 this.addr = addr; 118 this.port = port; 119 120 Assert.eval(this.addr != null); 121 } 122 123 public InetAddress getAddress() { 124 return addr; 125 } 126 127 public int getPort() { 128 return port; 129 } 130 131 public byte[] getAddressBytes() { 132 return addr.getAddress(); 133 } 134 135 public boolean equals(Object obj) { 136 if (obj instanceof TCSocketAddress) { 137 TCSocketAddress other = (TCSocketAddress) obj; 138 return ((this.port == other.port) && this.addr.equals(other.addr)); 139 } 140 return false; 141 } 142 143 public int hashCode() { 144 if (addr == null) { return super.hashCode(); } 145 146 return addr.hashCode() + port; 147 } 148 149 public String toString() { 150 return getStringForm(); 151 } 152 153 160 public String getStringForm() { 161 StringBuffer buf = new StringBuffer (); 162 buf.append(addr.getHostAddress()).append(":").append(port); 163 return buf.toString(); 164 } 165 166 public static boolean isValidPort(int port) { 167 return ((port >= 0) && (port <= 0xFFFF)); 168 } 169 170 private final InetAddress addr; 171 private final int port; 172 } | Popular Tags |