InetAddress.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. // INetAddress.java -- An Internet Protocol (IP) address.
  2. /* Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation
  3. This file is part of libgcj.
  4. This software is copyrighted work licensed under the terms of the
  5. Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
  6. details. */
  7. package java.net;
  8. import java.io.ObjectInputStream;
  9. import java.io.ObjectOutputStream;
  10. import java.io.IOException;
  11. import java.io.Serializable;
  12. import java.io.ObjectStreamException;
  13. /**
  14. * @author Per Bothner
  15. * @date January 6, 1999.
  16. */
  17. /*
  18. * Written using on-line Java Platform 1.2 API Specification, as well
  19. * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
  20. * (The latter turns out to have some errors ...)
  21. * Status: Believed complete and correct.
  22. *
  23. * @specnote This class is not final since JK 1.4
  24. */
  25. public class InetAddress implements Serializable
  26. {
  27. // The Serialized Form specifies that an int 'address' is saved/restored.
  28. // This class uses a byte array internally so we'll just do the conversion
  29. // at serialization time and leave the rest of the algorithm as is.
  30. private int address;
  31. transient byte[] addr;
  32. String hostName;
  33. // The field 'family' seems to be the AF_ value.
  34. // FIXME: Much of the code in the other java.net classes does not make
  35. // use of this family field. A better implementation would be to make
  36. // use of getaddrinfo() and have other methods just check the family
  37. // field rather than examining the length of the address each time.
  38. int family;
  39. private static final long serialVersionUID = 3286316764910316507L;
  40. /**
  41. * Needed for serialization
  42. */
  43. private void readResolve () throws ObjectStreamException
  44. {
  45. // FIXME: implement this
  46. }
  47. private void readObject(ObjectInputStream ois)
  48. throws IOException, ClassNotFoundException
  49. {
  50. ois.defaultReadObject();
  51. addr = new byte[4];
  52. addr[3] = (byte) address;
  53. for (int i = 2; i >= 0; --i)
  54. addr[i] = (byte) (address >>= 8);
  55. // Ignore family from serialized data. Since the saved address is 32 bits
  56. // the deserialized object will have an IPv4 address i.e. AF_INET family.
  57. // FIXME: An alternative is to call the aton method on the deserialized
  58. // hostname to get a new address. The Serialized Form doc is silent
  59. // on how these fields are used.
  60. family = getFamily (addr);
  61. }
  62. private void writeObject(ObjectOutputStream oos) throws IOException
  63. {
  64. // Build a 32 bit address from the last 4 bytes of a 4 byte IPv4 address
  65. // or a 16 byte IPv6 address.
  66. int len = addr.length;
  67. int i = len - 4;
  68. for (; i < len; i++)
  69. address = address << 8 | (((int) addr[i]) & 0xFF);
  70. oos.defaultWriteObject();
  71. }
  72. private static native int getFamily (byte[] address);
  73. InetAddress (byte[] address, String hostname)
  74. {
  75. addr = address;
  76. hostName = hostname;
  77. if (address != null)
  78. family = getFamily (address);
  79. }
  80. /**
  81. * Utility routine to check if the InetAddress is an IP multicast address
  82. *
  83. * @since 1.1
  84. */
  85. public boolean isMulticastAddress ()
  86. {
  87. int len = addr.length;
  88. if (len == 4)
  89. return (addr[0] & 0xF0) == 0xE0;
  90. if (len == 16)
  91. return addr[0] == (byte) 0xFF;
  92. return false;
  93. }
  94. /**
  95. * Utility routine to check if the InetAddress in a wildcard address
  96. *
  97. * @since 1.4
  98. */
  99. public boolean isAnyLocalAddress ()
  100. {
  101. // This is the IPv4 implementation.
  102. // Any class derived from InetAddress should override this.
  103. return addr == zeros;
  104. }
  105. /**
  106. * Utility routine to check if the InetAddress is a loopback address
  107. *
  108. * @since 1.4
  109. */
  110. public boolean isLoopbackAddress ()
  111. {
  112. // This is the IPv4 implementation.
  113. // Any class derived from InetAddress should override this.
  114. return addr[0] == 0x7F;
  115. }
  116. /**
  117. * Utility routine to check if InetAddress is a link local address
  118. *
  119. * @since 1.4
  120. */
  121. public boolean isLinkLocalAddress ()
  122. {
  123. // This is the IPv4 implementation.
  124. // Any class derived from InetAddress should override this.
  125. // XXX: This seems to not exist with IPv4 addresses
  126. return false;
  127. }
  128. /**
  129. * Utility routine to check if InetAddress is a site local address
  130. *
  131. * @since 1.4
  132. */
  133. public boolean isSiteLocalAddress ()
  134. {
  135. // This is the IPv4 implementation.
  136. // Any class derived from InetAddress should override this.
  137. // 10.0.0.0/8
  138. if (addr[0] == 0x0A)
  139. return true;
  140. // XXX: Suns JDK 1.4.1 (on Linux) seems to have a bug here:
  141. // it says 172.16.0.0 - 172.255.255.255 are site local addresses
  142. // 172.16.0.0/12
  143. if (addr[0] == 0xAC && (addr[1] & 0xF0) == 0x01)
  144. return true;
  145. // 192.168.0.0/16
  146. if (addr[0] == 0xC0 && addr[1] == 0xA8)
  147. return true;
  148. // XXX: Do we need to check more addresses here ?
  149. return false;
  150. }
  151. /**
  152. * Utility routine to check if InetAddress is a global multicast address
  153. *
  154. * @since 1.4
  155. */
  156. public boolean isMCGlobal ()
  157. {
  158. // This is the IPv4 implementation.
  159. // Any class derived from InetAddress should override this.
  160. // XXX: This seems to not exist with IPv4 addresses
  161. return false;
  162. }
  163. /**
  164. * Utility reoutine to check if InetAddress is a node local multicast address
  165. *
  166. * @since 1.4
  167. */
  168. public boolean isMCNodeLocal ()
  169. {
  170. // This is the IPv4 implementation.
  171. // Any class derived from InetAddress should override this.
  172. // XXX: This seems to not exist with IPv4 addresses
  173. return false;
  174. }
  175. /**
  176. * Utility reoutine to check if InetAddress is a link local multicast address
  177. *
  178. * @since 1.4
  179. */
  180. public boolean isMCLinkLocal ()
  181. {
  182. // This is the IPv4 implementation.
  183. // Any class derived from InetAddress should override this.
  184. if (!isMulticastAddress ())
  185. return false;
  186. return (addr[0] == 0xE0
  187. && addr[1] == 0x00
  188. && addr[2] == 0x00);
  189. }
  190. /**
  191. * Utility reoutine to check if InetAddress is a site local multicast address
  192. *
  193. * @since 1.4
  194. */
  195. public boolean isMCSiteLocal ()
  196. {
  197. // This is the IPv4 implementation.
  198. // Any class derived from InetAddress should override this.
  199. // XXX: This seems to not exist with IPv4 addresses
  200. return false;
  201. }
  202. /**
  203. * Utility reoutine to check if InetAddress is a organization local
  204. * multicast address
  205. *
  206. * @since 1.4
  207. */
  208. public boolean isMCOrgLocal ()
  209. {
  210. // This is the IPv4 implementation.
  211. // Any class derived from InetAddress should override this.
  212. // XXX: This seems to not exist with IPv4 addresses
  213. return false;
  214. }
  215. /**
  216. * Returns the hostname represented by this InetAddress
  217. */
  218. public String getHostName ()
  219. {
  220. if (hostName == null)
  221. lookup (null, this, false);
  222. return hostName;
  223. }
  224. /**
  225. * Returns the canonical hostname represented by this InetAddress
  226. *
  227. * @since 1.4
  228. */
  229. public String getCanonicalHostName ()
  230. {
  231. SecurityManager sm = System.getSecurityManager ();
  232. if (sm != null)
  233. {
  234. try
  235. {
  236. sm.checkConnect (hostName, -1);
  237. }
  238. catch (SecurityException e)
  239. {
  240. return getHostAddress ();
  241. }
  242. }
  243. // Try to find the FDQN now
  244. InetAddress address = new InetAddress (getAddress (), null);
  245. return address.getHostName ();
  246. }
  247. /**
  248. * Returns the IP address of this InetAddress as array of bytes
  249. */
  250. public byte[] getAddress ()
  251. {
  252. // An experiment shows that JDK1.2 returns a different byte array each
  253. // time. This makes sense, in terms of security.
  254. return (byte[]) addr.clone();
  255. }
  256. /* Helper function due to a CNI limitation. */
  257. private static InetAddress[] allocArray (int count)
  258. {
  259. return new InetAddress[count];
  260. }
  261. /* Helper function due to a CNI limitation. */
  262. private static SecurityException checkConnect (String hostname)
  263. {
  264. SecurityManager s = System.getSecurityManager();
  265. if (s == null)
  266. return null;
  267. try
  268. {
  269. s.checkConnect(hostname, -1);
  270. return null;
  271. }
  272. catch (SecurityException ex)
  273. {
  274. return ex;
  275. }
  276. }
  277. /**
  278. * Returns the IP address as string
  279. *
  280. * @since 1.0.2
  281. */
  282. public String getHostAddress ()
  283. {
  284. StringBuffer sbuf = new StringBuffer(40);
  285. int len = addr.length;
  286. int i = 0;
  287. if (len == 16)
  288. { // An IPv6 address.
  289. for (; ; i += 2)
  290. {
  291. if (i >= 16)
  292. return sbuf.toString();
  293. int x = ((addr[i] & 0xFF) << 8) | (addr[i+1] & 0xFF);
  294. boolean empty = sbuf.length() == 0;
  295. if (empty)
  296. {
  297. if (i == 10 && x == 0xFFFF)
  298. { // IPv4-mapped IPv6 address.
  299. sbuf.append(":FFFF:");
  300. break; // Continue as IPv4 address;
  301. }
  302. else if (i == 12)
  303. { // IPv4-compatible IPv6 address.
  304. sbuf.append(':');
  305. break; // Continue as IPv4 address.
  306. }
  307. else if (i > 0)
  308. sbuf.append("::");
  309. }
  310. else
  311. sbuf.append(':');
  312. if (x != 0 || i >= 14)
  313. sbuf.append(Integer.toHexString(x).toUpperCase());
  314. }
  315. }
  316. for ( ; ; )
  317. {
  318. sbuf.append(addr[i] & 0xFF);
  319. i++;
  320. if (i == len)
  321. break;
  322. sbuf.append('.');
  323. }
  324. return sbuf.toString();
  325. }
  326. /**
  327. * Returns a hashcode of the InetAddress
  328. */
  329. public int hashCode()
  330. {
  331. // There hashing algorithm is not specified, but a simple experiment
  332. // shows that it is equal to the address, as a 32-bit big-endian integer.
  333. int hash = 0;
  334. int len = addr.length;
  335. int i = len > 4 ? len - 4 : 0;
  336. for ( ; i < len; i++)
  337. hash = (hash << 8) | (addr[i] & 0xFF);
  338. return hash;
  339. }
  340. /**
  341. * Compares the InetAddress object with another one.
  342. */
  343. public boolean equals (Object obj)
  344. {
  345. if (obj == null || ! (obj instanceof InetAddress))
  346. return false;
  347. // "The Java Class Libraries" 2nd edition says "If a machine has
  348. // multiple names instances of InetAddress for different name of
  349. // that same machine are not equal. This is because they have
  350. // different host names." This violates the description in the
  351. // JDK 1.2 API documentation. A little experimentation
  352. // shows that the latter is correct.
  353. byte[] addr1 = addr;
  354. byte[] addr2 = ((InetAddress) obj).addr;
  355. if (addr1.length != addr2.length)
  356. return false;
  357. for (int i = addr1.length; --i >= 0; )
  358. if (addr1[i] != addr2[i])
  359. return false;
  360. return true;
  361. }
  362. /**
  363. * Returns then <code>InetAddress</code> as string
  364. */
  365. public String toString()
  366. {
  367. String result;
  368. String address = getHostAddress();
  369. if (hostName != null)
  370. result = hostName + "/" + address;
  371. else
  372. result = address;
  373. return result;
  374. }
  375. /**
  376. * Returns an InetAddress object given the raw IP address.
  377. *
  378. * The argument is in network byte order: the highest order byte of the
  379. * address is in getAddress()[0].
  380. *
  381. * @param addr The IP address to create the InetAddress object from
  382. *
  383. * @exception UnknownHostException If IP address has illegal length
  384. *
  385. * @since 1.4
  386. */
  387. public static InetAddress getByAddress(byte[] addr)
  388. throws UnknownHostException
  389. {
  390. if (addr.length != 4 && addr.length != 16)
  391. throw new UnknownHostException ("IP address has illegal length");
  392. if (addr.length == 4)
  393. return new Inet4Address (addr, null);
  394. return new Inet6Address (addr, null);
  395. }
  396. /**
  397. * Creates an InetAddress based on the provided host name and IP address.
  398. * No name service is checked for the validity of the address.
  399. *
  400. * @param host The hostname of the InetAddress object to create
  401. * @param addr The IP address to create the InetAddress object from
  402. *
  403. * @exception UnknownHostException If IP address is of illegal length
  404. *
  405. * @since 1.4
  406. */
  407. public static InetAddress getByAddress (String host, byte[] addr)
  408. throws UnknownHostException
  409. {
  410. if (addr.length == 4)
  411. return new Inet4Address (addr, host);
  412. if (addr.length == 16)
  413. return new Inet6Address (addr, host);
  414. throw new UnknownHostException ("IP address has illegal length");
  415. }
  416. /** If host is a valid numeric IP address, return the numeric address.
  417. * Otherwise, return null. */
  418. private static native byte[] aton (String host);
  419. private static native InetAddress[] lookup (String hostname,
  420. InetAddress addr, boolean all);
  421. /**
  422. * Determines the IP address of a host, given the host's name.
  423. *
  424. * @exception UnknownHostException If no IP address for the host could
  425. * be found
  426. * @exception SecurityException If a security manager exists and its
  427. * checkConnect method doesn't allow the operation
  428. */
  429. public static InetAddress getByName (String hostname)
  430. throws UnknownHostException
  431. {
  432. SecurityManager sm = System.getSecurityManager();
  433. if (sm != null)
  434. sm.checkConnect (hostname, -1);
  435. // Default to current host if necessary
  436. if (hostname == null)
  437. return getLocalHost();
  438. // Assume that the host string is an IP address
  439. byte[] address = aton (hostname);
  440. if (address != null)
  441. {
  442. if (address.length == 4)
  443. return new Inet4Address (address, null);
  444. else if (address.length == 16)
  445. {
  446. if ((address[10] == 0xFF) && (address[11] == 0xFF))
  447. {
  448. byte[] ip4addr = new byte[4];
  449. ip4addr[0] = address[12];
  450. ip4addr[1] = address[13];
  451. ip4addr[2] = address[14];
  452. ip4addr[3] = address[15];
  453. return new Inet4Address (ip4addr, null);
  454. }
  455. return new Inet6Address (address, null);
  456. }
  457. else
  458. throw new UnknownHostException ("Address has invalid length");
  459. }
  460. // Try to resolve the host by DNS
  461. InetAddress[] addresses = getAllByName (hostname);
  462. return addresses[0];
  463. }
  464. /**
  465. * Given the name of a host, returns an array of its IP addresses,
  466. * based on the configured name service on the system.
  467. *
  468. * @exception UnknownHostException If no IP address for the host could
  469. * be found
  470. * @exception SecurityException If a security manager exists and its
  471. * checkConnect method doesn't allow the operation
  472. */
  473. public static InetAddress[] getAllByName (String hostname)
  474. throws UnknownHostException
  475. {
  476. SecurityManager sm = System.getSecurityManager();
  477. if (sm != null)
  478. sm.checkConnect(hostname, -1);
  479. // Check if hostname is an IP address
  480. byte[] address = aton (hostname);
  481. if (address != null)
  482. {
  483. InetAddress[] result = new InetAddress[1];
  484. result[0] = new InetAddress(address, null);
  485. return result;
  486. }
  487. // Try to resolve the hostname by DNS
  488. return lookup (hostname, null, true);
  489. }
  490. static final byte[] zeros = {0,0,0,0};
  491. /* dummy InetAddress, used to bind socket to any (all) network interfaces */
  492. static final InetAddress ANY_IF = new InetAddress(zeros, null);
  493. private static final byte[] localhostAddress = { 127, 0, 0, 1 };
  494. private static native String getLocalHostname ();
  495. private static InetAddress localhost = null;
  496. /**
  497. * Returns the local host
  498. *
  499. * @exception UnknownHostException If no IP address for the host could
  500. * be found
  501. */
  502. public static InetAddress getLocalHost() throws UnknownHostException
  503. {
  504. SecurityManager s = System.getSecurityManager();
  505. // Experimentation shows that JDK1.2 does cache the result.
  506. // However, if there is a security manager, and the cached result
  507. // is other than "localhost", we need to check again.
  508. if (localhost == null
  509. || (s != null && localhost.addr != localhostAddress))
  510. getLocalHost(s);
  511. return localhost;
  512. }
  513. private static synchronized void getLocalHost(SecurityManager s)
  514. throws UnknownHostException
  515. {
  516. // Check the localhost cache again, now that we've synchronized.
  517. if (s == null && localhost != null)
  518. return;
  519. String hostname = getLocalHostname();
  520. if (s != null)
  521. {
  522. // "The Java Class Libraries" suggests that if the security
  523. // manager disallows getting the local host name, then
  524. // we use the loopback host.
  525. // However, the JDK 1.2 API claims to throw SecurityException,
  526. // which seems to suggest SecurityException is *not* caught.
  527. // In this case, experimentation shows that former is correct.
  528. try
  529. {
  530. // This is wrong, if the name returned from getLocalHostname()
  531. // is not a fully qualified name. FIXME.
  532. s.checkConnect(hostname, -1);
  533. }
  534. catch (SecurityException ex)
  535. {
  536. hostname = null;
  537. }
  538. }
  539. if (hostname != null)
  540. {
  541. try
  542. {
  543. localhost = new InetAddress(null, null);
  544. lookup(hostname, localhost, false);
  545. }
  546. catch (Exception ex)
  547. {
  548. }
  549. }
  550. if (localhost == null)
  551. localhost = new InetAddress (localhostAddress, "localhost");
  552. }
  553. }