Java获取IP地址 Java获取电脑真实IP地址的代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java获取IP地址 Java获取电脑真实IP地址的代码实例

H.U.C-王子   2021-03-16 我要评论
想了解Java获取电脑真实IP地址的代码实例的相关内容吗,H.U.C-王子在本文为您仔细讲解Java获取IP地址的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,ip地址,Java,获取IP地址,Java,获取真实IP地址,下面大家一起来学习吧。
/**
 * @author yins
 * @date 2018年8月12日下午9:53:58 
 */

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
 
/**
 * 获取本地真正的IP地址,即获得有线或者无线WiFi地址。
 * 过滤虚拟机、蓝牙等地址
 * @author yins
 * @date 2018年8月12日 下午9:53:58
 */
public class GetRealLocalIP {
 
  /**
   * 获取本地真正的IP地址,即获得有线或者无线WiFi地址。
   * 过滤虚拟机、蓝牙等地址
   * @author yins
   * @date 2018年8月12日下午9:56:35
   * @return
   */
  public static String getRealIP() {
    try {
      Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface
          .getNetworkInterfaces();
      while (allNetInterfaces.hasMoreElements()) {
        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces
            .nextElement();
 
        // 去除回环接口,子接口,未运行和接口
        if (netInterface.isLoopback() || netInterface.isVirtual()
            || !netInterface.isUp()) {
          continue;
        }
        
        if (!netInterface.getDisplayName().contains("Intel")
            && !netInterface.getDisplayName().contains("Realtek")) {
          continue;
        }
        Enumeration<InetAddress> addresses = netInterface
            .getInetAddresses();
        System.out.println(netInterface.getDisplayName());
        while (addresses.hasMoreElements()) {
          InetAddress ip = addresses.nextElement();
          if (ip != null) {
            // ipv4
            if (ip instanceof Inet4Address) {
              System.out.println("ipv4 = " + ip.getHostAddress());
              return ip.getHostAddress();
            }
          }
        }
        break;
      }
    } catch (SocketException e) {
      System.err.println("Error when getting host ip address"
          + e.getMessage());
    }
    return null;
  }
}

此代码中只要读取到了WiFi或者有线地址其中之一立即return。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们