java 如何獲取多網卡時的本機IP

public String getLocalHostName() {
        String hostName;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostName = addr.getHostName();
        } catch (Exception ex) {
            hostName = "";
        }
        return hostName;
    }

public String[] getAllLocalHostIP() {
    String[] ret = null;
    try {
        String hostName = getLocalHostName();
        if (hostName.length() > 0) {
            InetAddress[] addrs = InetAddress.getAllByName(hostName);
            if (addrs.length > 0) {
                ret = new String[addrs.length];
                for (int i = 0; i < addrs.length; i++) {
                    ret[i] = addrs[i].getHostAddress();
                }
            }
        }

        } catch (Exception ex) {
            ret = null;
        }
        return ret;
    }


以上代碼在WIN XP上測試通過,有機會在linux上測試一下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章