一、前言
关于keycloak的keycloak-common源码包org.keycloak.common.util.HostUtils主机工具类,获取主机名getHostName、获取ip地址getIpAddress、获取主机名称getHostNameImpl及获取本地地址getLocalHost等操作。
二、源码说明
package org.keycloak.common.util;@b@@b@import java.net.InetAddress;@b@import java.net.UnknownHostException; @b@ @b@public class HostUtils{@b@@b@    // Best effort to find the most proper hostname of this server.@b@    public static String getHostName() {@b@        return getHostNameImpl().trim().toLowerCase();@b@    }@b@@b@    public static String getIpAddress() {@b@        try {@b@            String hostname = getHostName();@b@            return InetAddress.getByName(hostname).getHostAddress();@b@        } catch (UnknownHostException uhe) {@b@            throw new IllegalStateException(uhe);@b@        }@b@    }@b@@b@    private static String getHostNameImpl() {@b@        // Return bind address if available@b@        String bindAddr = System.getProperty("jboss.bind.address");@b@        if (bindAddr != null && !bindAddr.trim().equals("0.0.0.0")) {@b@            return bindAddr;@b@        }@b@@b@        // Fallback to qualified name@b@        String qualifiedHostName = System.getProperty("jboss.qualified.host.name");@b@        if (qualifiedHostName != null) {@b@            return qualifiedHostName;@b@        }@b@@b@        // If not on jboss env, let's try other possible fallbacks@b@        // POSIX-like OSes including Mac should have this set@b@        qualifiedHostName = System.getenv("HOSTNAME");@b@        if (qualifiedHostName != null) {@b@            return qualifiedHostName;@b@        }@b@@b@        // Certain versions of Windows@b@        qualifiedHostName = System.getenv("COMPUTERNAME");@b@        if (qualifiedHostName != null) {@b@            return qualifiedHostName;@b@        }@b@@b@        try {@b@            return NetworkUtils.canonize(getLocalHost().getHostName());@b@        } catch (UnknownHostException uhe) {@b@            uhe.printStackTrace();@b@            return "unknown-host.unknown-domain";@b@        }@b@    }@b@@b@    /**@b@     * Methods returns InetAddress for localhost@b@     *@b@     * @return InetAddress of the localhost@b@     * @throws UnknownHostException if localhost could not be resolved@b@     */@b@    private static InetAddress getLocalHost() throws UnknownHostException {@b@        InetAddress addr;@b@        try {@b@            addr = InetAddress.getLocalHost();@b@        } catch (ArrayIndexOutOfBoundsException e) {  //this is workaround for mac osx bug see AS7-3223 and JGRP-1404@b@            addr = InetAddress.getByName(null);@b@        }@b@        return addr;@b@    }@b@}