请求ip获取工具类

package com.panchan.m2.utils;

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

/**
 * 工具类获取请求ip
 * @author panchankeji.hu
 *
 */
public class ServerIPConfigUtil {
    public static String getLocalIPForJava() {
        StringBuilder sb = new StringBuilder();
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface intf = (NetworkInterface) en.nextElement();
                Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
//                        if (!inetAddress.isLoopbackAddress()&& !inetAddress.isLinkLocalAddress()&& inetAddress.isSiteLocalAddress()) {
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipAddress = inetAddress.getHostAddress().toString();
                        if (ipAddress.startsWith("192.168")) {
                            sb.append(ipAddress);
                        }
//                            sb.append("|");
                    }
                }
            }
        } catch (SocketException e) {
        }
        return sb.toString();
    }

    public static String getLocalRealIP() {
        StringBuilder sb = new StringBuilder();
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface intf = (NetworkInterface) en.nextElement();
                Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
//                        if (!inetAddress.isLoopbackAddress()&& !inetAddress.isLinkLocalAddress()&& inetAddress.isSiteLocalAddress()) {
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipAddress = inetAddress.getHostAddress().toString();
                        sb.append(ipAddress);
//                            sb.append("|");
                    }
                }
            }
        } catch (SocketException e) {
        }
        return sb.toString();
    }


    /**
     * 获取服务器IP地址
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String getServerIp(){
        String SERVER_IP = null;
        try {
            InetAddress address = InetAddress.getLocalHost();
            SERVER_IP=address.getHostAddress();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return SERVER_IP;
    }
}

 

上一篇:群晖NAS之间复制或移动文件的方法及推荐方案


下一篇:Intenet 地址