zoukankan      html  css  js  c++  java
  • Java 获取本机IP

    Java 获取本机IP

    注意:代码中去除了127.0.0.1

    获取本机所有IP

    package com.airport.controller;
    
    import java.net.Inet4Address;
    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;
    
    public class TestController {
    
        /**
         * 获取本机IP
         *
         * @return List<String>
         * @author 云深小麦
         */
        private static List<String> getIp() {
            List<String> result = new ArrayList<>();
            try {
                Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                while (networkInterfaces.hasMoreElements()) {
                    NetworkInterface netInterface = networkInterfaces.nextElement();
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress ip = addresses.nextElement();
                        if (ip instanceof Inet4Address) {
                            String hostAddress = ip.getHostAddress();
                            // 去除127.0.0.1
                            if (!hostAddress.equals("127.0.0.1")) {
                                result.add(hostAddress);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                return null;
            }
            return result;
        }
    
        public static void main(String[] args) {
            for (String ip : getIp()) {
                System.out.println("本机IP: " + ip);
            }
    
        }
    }
    
    

    main方法输出

    本机IP: 192.168.31.12
    
  • 相关阅读:
    flex+spring3.0+blazds 数据推送整理版
    深入理解java虚拟机学习笔记1.
    一个netty序列化引起的思考。
    万年历
    面试理论题
    EF之Database First
    20120902 09:29 SQL、LINQ、Lambda 三种用法
    内容漂浮在图片上(div漂浮)
    生成订单号
    时间对比
  • 原文地址:https://www.cnblogs.com/guoqingyan/p/15765744.html
Copyright © 2011-2022 走看看