获取本机ip

package com.whj.common.util;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.ObjectName;

public class IpUtils {

    /**
     * windows服务器ip
     * 
     * @return
     * @throws UnknownHostException
     */
    public static String getWindowsLocalIp() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();

    }

    /**
     * linux服务器ip
     * 
     * @return
     * @throws UnknownHostException
     */
    public static String getLinuxLocalIp() throws SocketException {
        InetAddress ip = null;
        Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
        while (netInterfaces.hasMoreElements()) {

            NetworkInterface ni = netInterfaces.nextElement();
            // ----------特定情况,可以考虑用ni.getName判断
            String name = ni.getName();
            // System.out.println("name:》》"+name);
            if (name.contains("docker") || name.contains("lo")) {
                continue;
            }

            // 遍历所有ip
            Enumeration<InetAddress> ips = ni.getInetAddresses();
            while (ips.hasMoreElements()) {
                ip = (InetAddress) ips.nextElement();
                // System.out.println("ip:>>"+ip);
                String hostAddress = ip.getHostAddress();
                // System.out.println("hostAddress:>>"+hostAddress);
                if ((hostAddress.endsWith(".0")) || (hostAddress.endsWith(".1"))) {
                    continue;
                }
                if (hostAddress.contains("::") || hostAddress.contains("0:0:") || hostAddress.contains("fe80")) {
                    continue;
                }
                // 127.开头的都是lookback地址
                if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
                    // System.out.println(" target:>>"+ip);
                    return hostAddress;
                }
            }
        }
        throw new RuntimeException("Failed to get the server ip");
    }

    /**
     * 判断操作系统是否是Windows
     *
     * @return
     */
    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        // 注:这里的system,系统指的是 JRE (runtime)system,不是指 OS
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    /**
     * 获取本地IP地址
     *
     * @throws SocketException
     */
    public static String getLocalIP() throws UnknownHostException, SocketException {
        if (isWindowsOS()) {
            return getWindowsLocalIp();
        } else {
            return getLinuxLocalIp();
        }
    }

    public static String getMac() throws Exception {
        InetAddress ia = InetAddress.getLocalHost();
        // 获取网卡,获取地址        
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            // 字节转换为整数
            int temp = mac[i] & 0xff;
            String str = Integer.toHexString(temp);
            // System.out.println("每8位:"+str);
            if (str.length() == 1) {
                sb.append("0" + str);
            } else {
                sb.append(str);
            }
        }
        return sb.toString().toUpperCase();
    }

    public static String getPort() throws Exception {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = mBeanServer.queryNames(new ObjectName("*:type=Connector,*"), null);
        if (objectNames == null || objectNames.size() <= 0) {
            throw new IllegalStateException("Cannot get the names of MBeans controlled by the MBean server.");
        }
        for (ObjectName objectName : objectNames) {
            String protocol = String.valueOf(mBeanServer.getAttribute(objectName, "protocol"));
            String port = String.valueOf(mBeanServer.getAttribute(objectName, "port"));
            // windows下属性名称为HTTP/1.1, linux下为org.apache.coyote.http11.Http11NioProtocol
            if (protocol.equals("HTTP/1.1") || protocol.equals("org.apache.coyote.http11.Http11NioProtocol")) {
                return port;
            }
        }
        throw new IllegalStateException("Failed to get the HTTP port of the current server");
    }
    
    
    /**
     * 根据ip+端口号生成key
     * 
     * <p>无法获取ip和port时随机生成key
     * @return
     */
    public static String getServerKey(){
        String ip=null;
        String port=null;
        
        try {
            ip=getLocalIP();
        }catch(Exception e) {
            e.printStackTrace();
        }
        if(ip==null) {
            try {
                ip=getMac();
            }catch(Exception e) {
                e.printStackTrace();
                ip=RandomUtils.genarateStr(6, "SVR-");
            }
        }        
        
        try {
            port=getPort();
        }catch(Exception e) {
            e.printStackTrace();
            port=RandomUtils.genarateNumStr(4, null);
        }        
        return ip+":"+port;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(getWindowsLocalIp());
        System.out.println(getLinuxLocalIp());
        System.out.println(getMac());
        System.out.println(getServerKey());
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值