InetAddress.java 8.53 KB
Newer Older
Tom Tromey committed
1 2
// INetAddress.java -- An Internet Protocol (IP) address.

3
/* Copyright (C) 1998, 1999, 2000  Free Software Foundation
Tom Tromey committed
4 5 6 7 8 9 10 11

   This file is part of libgcj.

This software is copyrighted work licensed under the terms of the
Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
details.  */

package java.net;
12 13 14
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
Tom Tromey committed
15 16 17 18 19 20 21 22 23 24 25 26 27

/**
 * @author Per Bothner
 * @date January 6, 1999.
 */

/*
 * Written using on-line Java Platform 1.2 API Specification, as well
 * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
 * (The latter turns out to have some errors ...)
 * Status:  Believed complete and correct.
 */

28
public final class InetAddress implements java.io.Serializable
Tom Tromey committed
29
{
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
  // The Serialized Form specifies that an int 'address' is saved/restored.
  // This class uses a byte array internally so we'll just do the conversion
  // at serialization time and leave the rest of the algorithm as is.
  private int address;
  transient byte[] addr;
  String hostName;
  // The field 'family' seems to be the AF_ value.
  // FIXME: Much of the code in the other java.net classes does not make
  // use of this family field.  A better implementation would be to make
  // use of getaddrinfo() and have other methods just check the family
  // field rather than examining the length of the address each time.
  int family;
  private static final long serialVersionUID = 3286316764910316507L;

  private void readObject(ObjectInputStream ois)
    throws IOException, ClassNotFoundException
  {
    ois.defaultReadObject();
    addr = new byte[4];
    addr[3] = (byte) address;
    for (int i = 2; i >= 0; --i)
      addr[i] = (byte) (address >>= 8);
    // Ignore family from serialized data.  Since the saved address is 32 bits
    // the deserialized object will have an IPv4 address i.e. AF_INET family.
    // FIXME: An alternative is to call the aton method on the deserialized
    // hostname to get a new address.  The Serialized Form doc is silent
    // on how these fields are used.
    family = getFamily (addr);
  }

  private void writeObject(ObjectOutputStream oos) throws IOException
  {
    // Build a 32 bit address from the last 4 bytes of a 4 byte IPv4 address
    // or a 16 byte IPv6 address.
    int len = addr.length;
    int i = len - 4;
    for (; i < len; i++)
      address = address << 8 | (((int) addr[i]) & 0xFF);
    oos.defaultWriteObject();
  }

  private static native int getFamily (byte[] address);
Tom Tromey committed
72 73 74

  InetAddress (byte[] address, String hostname)
  {
75 76 77 78
    addr = address;
    hostName = hostname;
    if (address != null)
      family = getFamily (address);
Tom Tromey committed
79 80 81 82
  }

  public boolean isMulticastAddress ()
  {
83
    int len = addr.length;
Tom Tromey committed
84
    if (len == 4)
85
      return (addr[0] & 0xF0) == 0xE0;
Tom Tromey committed
86
    if (len == 16)
87
      return addr[0] == (byte) 0xFF;
Tom Tromey committed
88 89 90 91 92
    return false;
  }

  public String getHostName ()
  {
93
    if (hostName == null)
Tom Tromey committed
94
      lookup (null, this, false);
95
    return hostName;
Tom Tromey committed
96 97 98 99 100 101
  }

  public byte[] getAddress ()
  {
    // An experiment shows that JDK1.2 returns a different byte array each
    // time.  This makes sense, in terms of security.
102
    return (byte[]) addr.clone();
Tom Tromey committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  }

  /* Helper function due to a CNI limitation.  */
  private static InetAddress[] allocArray (int count)
  {
    return new InetAddress[count];
  }

  /* Helper function due to a CNI limitation.  */
  private static SecurityException checkConnect (String hostname)
  {
    SecurityManager s = System.getSecurityManager();
    if (s == null)
      return null;
    try
      {
	s.checkConnect(hostname, -1);
	return null;
      }
    catch (SecurityException ex)
      {
	return ex;
      }
  }

  public String getHostAddress ()
  {
    StringBuffer sbuf = new StringBuffer(40);
131
    int len = addr.length;
Tom Tromey committed
132 133 134 135 136 137 138
    int i = 0;
    if (len == 16)
      { // An IPv6 address.
	for (;  ;  i += 2)
	  {
	    if (i >= 16)
	      return sbuf.toString();
139
	    int x = ((addr[i] & 0xFF) << 8) | (addr[i+1] & 0xFF);
Tom Tromey committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
	    boolean empty = sbuf.length() == 0;
	    if (empty)
	      {
		if (i == 10 && x == 0xFFFF)
		  { // IPv4-mapped IPv6 address.
		    sbuf.append(":FFFF:");
		    break;  // Continue as IPv4 address;
		  }
		else if (i == 12)
		  { // IPv4-compatible IPv6 address.
		    sbuf.append(':');
		    break;  // Continue as IPv4 address.
		  }
		else if (i > 0)
		  sbuf.append("::");
	      }
	    else
	      sbuf.append(':');
	    if (x != 0 || i >= 14)
	      sbuf.append(Integer.toHexString(x).toUpperCase());
	  }
      }
    for ( ;  ; )
      {
164
	sbuf.append(addr[i] & 0xFF);
Tom Tromey committed
165 166 167 168 169 170 171 172 173 174 175 176 177
	i++;
	if (i == len)
	  break;
	sbuf.append('.');
      }
    return sbuf.toString();
  }

  public int hashCode()
  {
    // There hashing algorithm is not specified, but a simple experiment
    // shows that it is equal to the address, as a 32-bit big-endian integer.
    int hash = 0;
178
    int len = addr.length;
Tom Tromey committed
179 180
    int i = len > 4 ? len - 4 : 0;
    for ( ; i < len;  i++)
181
      hash = (hash << 8) | (addr[i] & 0xFF);
Tom Tromey committed
182 183 184 185 186 187 188 189 190 191 192 193 194
    return hash;
  }

  public boolean equals (Object obj)
  {
    if (obj == null || ! (obj instanceof InetAddress))
      return false;
    // "The Java Class Libraries" 2nd edition says "If a machine has
    // multiple names instances of InetAddress for different name of
    // that same machine are not equal.  This is because they have
    // different host names."  This violates the description in the
    // JDK 1.2 API documentation.  A little experiementation
    // shows that the latter is correct.
195 196
    byte[] addr1 = addr;
    byte[] addr2 = ((InetAddress) obj).addr;
Tom Tromey committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    if (addr1.length != addr2.length)
      return false;
    for (int i = addr1.length;  --i >= 0;  )
      if (addr1[i] != addr2[i])
	return false;
    return true;
  }

  public String toString()
  {
    return getHostName()+'/'+getHostAddress();
  }

  /** If host is a valid numeric IP address, return the numeric address.
   * Otherwise, return null. */
  private static native byte[] aton (String host);

  private static native InetAddress[] lookup
  (String hostname, InetAddress addr, boolean all);

  public static InetAddress getByName (String host)
    throws UnknownHostException
  {
    if (host == null)
      return getLocalHost();
    byte[] address = aton(host);
    if (address != null)
      return new InetAddress(address, null);
225
    InetAddress iaddr = new InetAddress(null, host);
Tom Tromey committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    lookup(host, iaddr, false);
    return iaddr;
  }

  public static InetAddress[] getAllByName (String host)
    throws UnknownHostException
  {
    byte[] address = aton(host);
    if (address != null)
      {
	InetAddress[] result = new InetAddress[1];
	result[0] = new InetAddress(address, null);
	return result;
      }
    return lookup(host, null, true);
  }

243 244 245 246
  static final byte[] zeros = {0,0,0,0};
  /* dummy InetAddress, used to bind socket to any (all) network interfaces */
  static final InetAddress ANY_IF = new InetAddress(zeros, null);
    
Tom Tromey committed
247 248 249 250 251 252 253 254 255 256 257 258 259
  private static final byte[] localhostAddress = { 127, 0, 0, 1 };

  private static native String getLocalHostname ();

  private static InetAddress localhost = null;

  public static InetAddress getLocalHost() throws UnknownHostException
  {
    SecurityManager s = System.getSecurityManager();
    // Experimentation shows that JDK1.2 does cache the result.
    // However, if there is a security manager, and the cached result
    // is other than "localhost", we need to check again.
    if (localhost == null
260
	|| (s != null && localhost.addr != localhostAddress))
Tom Tromey committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
      getLocalHost(s);
    return localhost;
  }

  private static synchronized void getLocalHost(SecurityManager s)
    throws UnknownHostException
  {
    // Check the localhost cache again, now that we've synchronized.
    if (s == null && localhost != null)
      return;
    String hostname = getLocalHostname();
    if (s != null)
      {
	// "The Java Class Libraries" suggests that if the security
	// manager disallows getting the local host name, then
	// we use the loopback host.
	// However, the JDK 1.2 API claims to throw SecurityException,
	// which seems to suggest SecurityException is *not* caught.
	// In this case, experimentation shows that former is correct.
	try
	  {
	    // This is wrong, if the name returned from getLocalHostname()
	    // is not a fully qualified name.  FIXME.
	    s.checkConnect(hostname, -1);
	  }
	catch (SecurityException ex)
	  {
	    hostname = null;
	  }
      }
    if (hostname != null)
      {
	try
	  {
295 296
	    localhost = new InetAddress(null, null);
	    lookup(hostname, localhost, false);
Tom Tromey committed
297 298 299 300 301 302 303 304 305
	  }
	catch (Exception ex)
	  {
	  }
      }
    if (localhost == null)
      localhost = new InetAddress (localhostAddress, "localhost");
  }
}