1 7 8 package org.sapia.ubik.util; 9 10 import java.net.InetAddress ; 11 import java.net.NetworkInterface ; 12 import java.net.SocketException ; 13 import java.net.UnknownHostException ; 14 import java.util.Enumeration ; 15 import java.util.regex.Pattern ; 16 17 import org.sapia.ubik.rmi.Consts; 18 import org.sapia.ubik.rmi.server.Log; 19 20 36 public class Localhost { 37 38 private static String LOCALHOST = "0.0.0.0"; 39 private static String LOOPBACK = "127.0.0.1"; 40 private static Pattern DEFAULT_IP_PATTERN = Pattern.compile("\\d+\\.\\d+\\.\\d+\\.\\d+"); 41 private static Pattern _pattern = DEFAULT_IP_PATTERN; 42 43 static{ 44 String patternStr = System.getProperty(Consts.IP_PATTERN_KEY); 45 if(patternStr != null){ 46 if(Log.isDebug()){ 47 Log.debug(Localhost.class, "Got local network address pattern: " + patternStr); 48 } 49 _pattern = Pattern.compile(patternStr); 50 } 51 } 52 53 56 public static InetAddress getLocalAddress() throws UnknownHostException { 57 NetworkInterface iface; 58 try{ 59 for(Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();){ 60 iface = (NetworkInterface )ifaces.nextElement(); 61 InetAddress ia = null; 62 for(Enumeration ips = iface.getInetAddresses(); ips.hasMoreElements();){ 63 ia = (InetAddress )ips.nextElement(); 64 String addr = ia.getHostAddress(); 65 if(addr.equals(LOCALHOST) || addr.equals(LOOPBACK)){ 66 continue; 67 } 68 if(isLocalAddress(_pattern, addr)){ 69 if(Log.isDebug()){ 70 Log.debug(Localhost.class, "Address " + addr + " matches: " + _pattern.toString()); 71 } 72 return ia; 73 } 74 } 75 } 76 }catch(SocketException e){} 77 return InetAddress.getLocalHost(); 78 } 79 80 static boolean isLocalAddress(Pattern pattern, String addr){ 81 return pattern.matcher(addr).matches(); 82 } 83 84 } 85 | Popular Tags |