java获取当前主机的物理地址(windows和linux均可)

时间:2022-10-14 17:36:08

package com.jungle.address.test;


import java.net.Inet4Address;

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;


public class AddressUtil {


privatefinal static StringNEED_CLEAR_IP ="127.0.0.1";

public static String getHostAddress() {

    Enumeration<NetworkInterface> allNetInterfaces;

    try {

      allNetInterfaces = NetworkInterface.getNetworkInterfaces();

    } catch (SocketExceptione) {

      returnnull;

    }

    if (allNetInterfaces ==null) {

      returnnull;

    }

    while (allNetInterfaces.hasMoreElements()) {

      NetworkInterface networkInterface = allNetInterfaces.nextElement();

      Enumeration<InetAddress> address = networkInterface.getInetAddresses();

      InetAddress ip = null;

      while (address.hasMoreElements()) {

        ip =address.nextElement();

        if (ip !=null && ip instanceof Inet4Address) {

          String hostAddress = ip.getHostAddress();

          if (!NEED_CLEAR_IP.equals(hostAddress)) {

            returnhostAddress;

          }

        }

      }

    }

    returnnull;

  }


  public static void main(String[] args) {

  System.out.println(getHostAddress());

  }

}