java如何查询本机ip地址和mac地址

Python050

java如何查询本机ip地址和mac地址,第1张

// 获取mac地址

  public static String getMacAddress() {

    try {

      Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces()

      byte[] mac = null

      while (allNetInterfaces.hasMoreElements()) {

        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement()

        if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {

          continue

        } else {

          mac = netInterface.getHardwareAddress()

          if (mac != null) {

            StringBuilder sb = new StringBuilder()

            for (int i = 0 i < mac.length i++) {

              sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""))

            }

            if (sb.length() > 0) {

              return sb.toString()

            }

          }

        }

      }

    } catch (Exception e) {

      _logger.error("MAC地址获取失败", e)

    }

    return ""

  }

 

  // 获取ip地址

  public static String getIpAddress() {

    try {

      Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces()

      InetAddress ip = null

      while (allNetInterfaces.hasMoreElements()) {

        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement()

        if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {

          continue

        } else {

          Enumeration<InetAddress> addresses = netInterface.getInetAddresses()

          while (addresses.hasMoreElements()) {

            ip = addresses.nextElement()

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

              return ip.getHostAddress()

            }

          }

        }

      }

    } catch (Exception e) {

      _logger.error("IP地址获取失败", e)

    }

    return ""

  }

希望能帮助到你

第一种:获取本机的IP

Enumeration<NetworkInterface>

netInterfaces

=

null

try

{

netInterfaces

=

NetworkInterface.getNetworkInterfaces()

while

(netInterfaces.hasMoreElements())

{

NetworkInterface

ni

=

netInterfaces.nextElement()

System.out.println("DisplayName:"

+

ni.getDisplayName())

System.out.println("Name:"

+

ni.getName())

Enumeration<InetAddress>

ips

=

ni.getInetAddresses()

while

(ips.hasMoreElements())

{

System.out.println("IP:"

+

ips.nextElement().getHostAddress())

ipTemp=

ni.getInetAddresses().nextElement().getHostAddress()

if(ipTemp!="127.0.0.1"

&&

!"127.0.0.1".equals(ipTemp))

{

ip=ipTemp

}

}

}

}catch(Exception

ee)

{

ee.printStackTrace()

}

第二种:也是本机的:

InetAddress

addr

=

InetAddress.getLocalHost()

ip=addr.getHostAddress().toString()//获得本机IP