1 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 41 public class InetAddressUtil { 42 private static Logger logger = 43 Logger.getLogger(InetAddressUtil.class.getName()); 44 45 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 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 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 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.getHostName()); 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 } | Popular Tags |