獲取服務器IP

package com.techsun.hennessy.common.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 獲取服務器IP
 */
public class GetHostIP {
	
	/**
	 * 判斷是windows還是Linux
	 * @return
	 */
	private static boolean isWindowOS() {
        boolean isWindowOS = false;
        String osName = System.getProperty("os.name");
        if(osName.toLowerCase().indexOf("windows") > -1) {
            isWindowOS = true;
        }
        return isWindowOS;
    }
    
    private static InetAddress getInetAddress() {
        InetAddress inetAddress = null;
        try {
            //如果是windows操作系統
            if (isWindowOS()) {
                inetAddress = InetAddress.getLocalHost();
            } else {
                boolean bFindIP = false;
                //定義一個內容都是NetworkInterface的枚舉對象
                Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>)
                        NetworkInterface.getNetworkInterfaces();
                //如果枚舉對象裏面還有內容(NetworkInterface)
                while (netInterfaces.hasMoreElements()) {
                    if (bFindIP) {
                        break;
                    }
                    //獲取下一個內容(NetworkInterface)
                    NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                    //----------特定情況,可以考慮用ni.getName判斷
                    //遍歷所有IP
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        inetAddress = (InetAddress) ips.nextElement();
                        if (inetAddress.isSiteLocalAddress()         //屬於本地地址
                                && !inetAddress.isLoopbackAddress()  //不是迴環地址
                                && inetAddress.getHostAddress().indexOf(":") == -1) {   //地址裏面沒有:號
                            bFindIP = true;     //找到了地址
                            break;              //退出循環
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inetAddress;
    }
    
    public static String getLocalIP() {
        return getInetAddress().getHostAddress();
    }
    
//    public static void main(String[] args){
//    	
//    	System.out.println(getLocalIP());
//    }
    
}

親測,有用!

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