1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.archive.util;
24
25 import java.net.InetAddress;
26 import java.net.NetworkInterface;
27 import java.net.SocketException;
28 import java.net.UnknownHostException;
29 import java.util.ArrayList;
30 import java.util.Enumeration;
31 import java.util.List;
32 import java.util.logging.Logger;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35
36 /***
37 * InetAddress utility.
38 * @author stack
39 * @version $Date: 2009-08-27 23:45:31 +0000 (Thu, 27 Aug 2009) $, $Revision: 6477 $
40 */
41 public class InetAddressUtil {
42 private static Logger logger =
43 Logger.getLogger(InetAddressUtil.class.getName());
44
45 /***
46 * ipv4 address.
47 */
48 public static Pattern IPV4_QUADS = Pattern.compile(
49 "([0-9]{1,3})//.([0-9]{1,3})//.([0-9]{1,3})//.([0-9]{1,3})");
50
51 private InetAddressUtil () {
52 super();
53 }
54
55 /***
56 * Returns InetAddress for passed <code>host</code> IF its in
57 * IPV4 quads format (e.g. 128.128.128.128).
58 * <p>TODO: Move to an AddressParsingUtil class.
59 * @param host Host name to examine.
60 * @return InetAddress IF the passed name was an IP address, else null.
61 */
62 public static InetAddress getIPHostAddress(String host) {
63 InetAddress result = null;
64 Matcher matcher = IPV4_QUADS.matcher(host);
65 if (matcher == null || !matcher.matches()) {
66 return result;
67 }
68 try {
69
70 result = InetAddress.getByAddress(host,
71 new byte[] {
72 (byte)(new Integer(matcher.group(1)).intValue()),
73 (byte)(new Integer(matcher.group(2)).intValue()),
74 (byte)(new Integer(matcher.group(3)).intValue()),
75 (byte)(new Integer(matcher.group(4)).intValue())});
76 } catch (NumberFormatException e) {
77 logger.warning(e.getMessage());
78 } catch (UnknownHostException e) {
79 logger.warning(e.getMessage());
80 }
81 return result;
82 }
83
84 /***
85 * @return All known local names for this host or null if none found.
86 */
87 public static List<String> getAllLocalHostNames() {
88 List<String> localNames = new ArrayList<String>();
89 Enumeration e = null;
90 try {
91 e = NetworkInterface.getNetworkInterfaces();
92 } catch(SocketException exception) {
93 throw new RuntimeException(exception);
94 }
95 for (; e.hasMoreElements();) {
96 for (Enumeration ee =
97 ((NetworkInterface)e.nextElement()).getInetAddresses();
98 ee.hasMoreElements();) {
99 InetAddress ia = (InetAddress)ee.nextElement();
100 if (ia != null) {
101 if (ia.getHostName() != null) {
102 localNames.add(ia.getCanonicalHostName());
103 }
104 if (ia.getHostAddress() != null) {
105 localNames.add(ia.getHostAddress());
106 }
107 }
108 }
109 }
110 final String localhost = "localhost";
111 if (!localNames.contains(localhost)) {
112 localNames.add(localhost);
113 }
114 final String localhostLocaldomain = "localhost.localdomain";
115 if (!localNames.contains(localhostLocaldomain)) {
116 localNames.add(localhostLocaldomain);
117 }
118 return localNames;
119 }
120 }