java获取本机器的IP(linux和windows)

[toc]

描述

由于项目是部署在集群上的,需要项目能够自动采集各机器的信息。java.net.InetAddress.getLocalHost()来获取本地机器的IP和机器名信息,但发现在linux下并不能获取到机器的实际IP和机器名信息(获取到的是localhost/127.0.0.1)。

方案描述

根据系统类型(linux、windows)来通过不同的方式获取本地机器的IP信息。

获取Windows下的IP

java.net.InetAddress.getLocalHost().getHostAddress();

获取linux下的IP

    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     * @throws SocketException
     */
    private static String getLinuxLocalIp() throws SocketException {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
                                    && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            ip = "127.0.0.1";
            ex.printStackTrace();
        }
        return 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;
    }

这里关于System.getProperty("os.name")说明一下(参考自http://blog.csdn.net/brotherdong90/article/details/49073941)

key 注释
file.separator File separator (e.g., "/")
java.class.path Java classpath
java.class.version Java class version number
java.home Java installation directory
java.vendor Java vendor-specific string
java.vendor.url Java vendor URL
java.version Java version number
line.separator Line separator
os.arch Operating system architecture
os.name Operating system name
path.separator Path separator (e.g., ":")
user.dir User‘s current working directory
user.home User home directory
user.name User account name

最后将上面三个方法进行整合

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

参考

https://www.cnblogs.com/raphael5200/p/5996464.html

原文地址:https://www.cnblogs.com/wsygdb/p/8393777.html

时间: 2024-08-08 14:41:46

java获取本机器的IP(linux和windows)的相关文章

java 获取公网(外网IP)很实用!

package com.lovo.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class PublicInterIp { /** * @param args * @throws Exception */ public S

java获取mac地址-屏蔽ip封mac地址

首先要说的是:可以支持外网机器的mac地址获取.  以前弄了一个只能访问局域网. 有防火墙就访问不了, 但是这个不用担心了. 测试了百度的ip,已经可以获得mac地址 测试效果图: java通过ip获取mac地址-封ip封mac地址 版权声明:本文为博主http://www.zuiniusn.com原创文章,未经博主允许不得转载.

Java获取本机的IP与MAC地址

有些机器有许多虚拟的网卡,获取IP地址时会出现一些意外,所以需要一些验证: 1 // 获取mac地址 2 public static String getMacAddress() { 3 try { 4 Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces(); 5 byte[] mac = null; 6 while (allNetInterfaces.hasMoreEle

java获取当前机器的公网ip

package com.Interface.util; import javax.servlet.http.HttpServletRequest; /** * 测试类 * * @author 华文 * @date 2019年7月5日 * @version 1.0 */ public class Test { /** * 获取当前公网ip */ public static String getIpAddr(HttpServletRequest request) { String ip = requ

Java获取操作系统的本机ip和Mac地址

获取局域网ip和mac(如果电脑没有直接连接外网),否则获取公网ip 通过第三放获取公网ip package org.twt.zipjar.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Inet4Address; import java.net.InetAdd

Java获取本机的ip地址

说到获取ip地址,有人可能会想到,直接用InetAddress.getLocalHost().getHostAddress().实际上这个是不对的,因为一台机器上可能有多个网络接口(一般指网卡或者虚拟网卡),因此也就有多个ip地址,所以我们需要列出所有的网络接口及其对应的ip地址.代码如下: public static void main(String[] args) throws Exception { Enumeration<NetworkInterface> netInterfaces

java 获取客户端的真实ip

直接上代码了: String ip = null; if (request.getHeader("X-Real-IP") == null) { ip = request.getRemoteHost(); } else { ip = request.getHeader("X-Real-IP"); }

java如何获取当前机器ip和容器port

获取当前机器ip: private static String getIpAddress() throws UnknownHostException { InetAddress address = InetAddress.getLocalHost(); return address.getHostAddress(); } 获取容器port: String port = String.valueOf(request.getLocalPort());

Java获取网络IP

Java获取获取网络IP,浅尝辄止咯- 1 import java.net.InetAddress; 2 import java.net.UnknownHostException; 3 4 /** 5 * 获取网络IP 6 * 1.获取本地的IP地址 7 * 2.获取本机的服务器名称 8 * 3.获取远程服务器的主机IP地址 9 * 4.获取远程服务器的所有主机IP 10 * 11 * 网络编程: 12 * InetAddress 是用来封装IP地址相关信息的类 13 * getLocalHos