---
title: "获取本机的IP地址（去除127.0.0.1）"
author: "e_e"
date: "2017-08-31T11:55:46Z"
tags: []
categories: ["编程语言"]
slug: "ip-127-0-0-1"
draft: false
lastmod: "2017-08-31T11:55:46Z"
id: 2391723
url: "https://e-e.iteye.com/blog/2391723"
---

/\**

 * Created by zhangyan on 2017/8/31.

 \*/

public class IpTool {

 

    private static final Logger LOG = Logger.getLogger(IpTool.class);

 

    public static String getLocalInet4Address() throws BaseException{

        try {

            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();

            InetAddress ipAddress = null;

            String ip = null;

            while (allNetInterfaces.hasMoreElements())

            {

                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();

                //System.out.println(netInterface.getName());

                Enumeration addresses = netInterface.getInetAddresses();

                while (addresses.hasMoreElements())

                {

                    ipAddress = (InetAddress) addresses.nextElement();

                    if (ipAddress != null && ipAddress instanceof Inet4Address)

                    {

                        if( ipAddress.getHostAddress().equals("127.0.0.1")){

                            continue;

                        }else{

                            ip =  ipAddress.getHostAddress();

                            System.out.println("本机的IP = " + ipAddress.getHostAddress());

                        }

                    }

                }

            }

            return ip;

        } catch (SocketException e) {

            LOG.error("【IpTool.getLocalInet4Address】获取IP地址异常");

            throw new BaseException(Code.GET\_IP\_ERROR);

        }

    }

}