栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

java获取本机IP

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java获取本机IP

如果在Windows系统环境下,当然可以直接通过InetAddress.getLocalHost()方法直接获取。

import java.net.InetAddress;
 
public class Main {
   public static void main(String[] args) 
   throws Exception {
      InetAddress addr = InetAddress.getLocalHost();
      System.out.println("Local HostAddress: 
      "+addr.getHostAddress());
      String hostname = addr.getHostName();
      System.out.println("Local host name: "+hostname);
   }
}

运行结果是:

Local HostAddress: 169.254.52.252
Local host name: LAPTOP-RV008F14

但是上述获取ip的方式有时候会得到127.0.0.1
Java提供了一个NetworkInterface类。这个类可以得到本地所有的物理网络接口和虚拟机等软件利用本机的物理网络接口创建的逻辑网络接口,NetworkInterface可以通过getNetworkInterfaces方法来枚举本地所有的网络接口。我们也可以利用getNetworkInterfaces得到网络接口来枚举本机的所有ip地址。

public static Enumeration getNetworkInterfaces() throws SocketException

getInterfaceAdresses()方法
这个方法用来获取此网络接口的全部或部分InterfaceAddresses的列表。

public List getInterfaceAddresses()

写一个获取IP的util类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.Enumeration;
import java.util.List;


public class IPHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(IPHelper.class);

    private static String hostIp;

    static {
        String ip = null;
        Enumeration allNetInterfaces;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = (NetworkInterface) allNetInterfaces.nextElement();
                //netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp() 用于排除回送接口,非虚拟网卡,未在使用中的网络接口.
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || networkInterface.isUp()) {
                	continue;
                }
                List interfaceAddresses = networkInterface.getInterfaceAddresses();
                for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                    InetAddress inetAddress = interfaceAddress.getAddress();
                    if (inetAddress instanceof Inet4Address) {
                        if (StringUtils.equals(inetAddress.getHostAddress(), "127.0.0.1")) {
                            continue;
                        }
                        ip = inetAddress.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        hostIp = ip;
    }

    public static String localIp() {
        return hostIp;
    }
}

本文参考:
https://blog.csdn.net/nianbingsihan/article/details/80265029

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/422461.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号