001
014
015 package com.liferay.portal.kernel.util;
016
017 import com.liferay.portal.kernel.exception.SystemException;
018
019 import java.net.Inet4Address;
020 import java.net.InetAddress;
021 import java.net.NetworkInterface;
022 import java.net.UnknownHostException;
023
024 import java.util.Enumeration;
025
026
030 public class InetAddressUtil {
031
032 public static String getLocalHostName() throws Exception {
033 return LocalHostNameHolder._LOCAL_HOST_NAME;
034 }
035
036 public static InetAddress getLocalInetAddress() throws Exception {
037 Enumeration<NetworkInterface> enu1 =
038 NetworkInterface.getNetworkInterfaces();
039
040 while (enu1.hasMoreElements()) {
041 NetworkInterface networkInterface = enu1.nextElement();
042
043 Enumeration<InetAddress> enu2 = networkInterface.getInetAddresses();
044
045 while (enu2.hasMoreElements()) {
046 InetAddress inetAddress = enu2.nextElement();
047
048 if (!inetAddress.isLoopbackAddress() &&
049 (inetAddress instanceof Inet4Address)) {
050
051 return inetAddress;
052 }
053 }
054 }
055
056 throw new SystemException("No local internet address");
057 }
058
059 public static InetAddress getLoopbackInetAddress()
060 throws UnknownHostException {
061
062 return InetAddress.getByName("127.0.0.1");
063 }
064
065 private static class LocalHostNameHolder {
066
067 private static final String _LOCAL_HOST_NAME;
068
069 static {
070 try {
071 InetAddress inetAddress = getLocalInetAddress();
072
073 _LOCAL_HOST_NAME = inetAddress.getHostName();
074 }
075 catch (Exception e) {
076 throw new ExceptionInInitializerError(e);
077 }
078 }
079
080 }
081
082 }