001
014
015 package com.liferay.portal.kernel.util;
016
017 import com.liferay.portal.kernel.exception.SystemException;
018 import com.liferay.portal.kernel.log.Log;
019 import com.liferay.portal.kernel.log.LogFactoryUtil;
020
021 import java.net.Inet4Address;
022 import java.net.InetAddress;
023 import java.net.NetworkInterface;
024 import java.net.UnknownHostException;
025
026 import java.util.Enumeration;
027
028
032 public class InetAddressUtil {
033
034 public static String getLocalHostName() throws Exception {
035 return LocalHostNameHolder._localHostName;
036 }
037
038 public static InetAddress getLocalInetAddress() throws Exception {
039 String clusterNodeListenAddress = StringPool.BLANK;
040
041 try {
042 clusterNodeListenAddress = GetterUtil.getString(
043 PropsUtil.get("cluster.node.listen.address"));
044 }
045 catch (Exception e) {
046 if (_log.isDebugEnabled()) {
047 _log.debug(e, e);
048 }
049 }
050
051 if (Validator.isNotNull(clusterNodeListenAddress)) {
052 InetAddress inetAddress = InetAddress.getByName(
053 clusterNodeListenAddress);
054
055 return inetAddress;
056 }
057
058 Enumeration<NetworkInterface> enu1 =
059 NetworkInterface.getNetworkInterfaces();
060
061 while (enu1.hasMoreElements()) {
062 NetworkInterface networkInterface = enu1.nextElement();
063
064 Enumeration<InetAddress> enu2 = networkInterface.getInetAddresses();
065
066 while (enu2.hasMoreElements()) {
067 InetAddress inetAddress = enu2.nextElement();
068
069 if (!inetAddress.isLoopbackAddress() &&
070 (inetAddress instanceof Inet4Address)) {
071
072 return inetAddress;
073 }
074 }
075 }
076
077 throw new SystemException("No local internet address");
078 }
079
080 public static InetAddress getLoopbackInetAddress()
081 throws UnknownHostException {
082
083 return InetAddress.getByName("127.0.0.1");
084 }
085
086 private static Log _log = LogFactoryUtil.getLog(InetAddressUtil.class);
087
088 private static class LocalHostNameHolder {
089
090 private static final String _localHostName;
091
092 static {
093 try {
094 InetAddress inetAddress = getLocalInetAddress();
095
096 _localHostName = inetAddress.getHostName();
097 }
098 catch (Exception e) {
099 throw new ExceptionInInitializerError(e);
100 }
101 }
102
103 }
104
105 }