怎样获取本机的真实IP地址

来源:互联网 发布:linux 获取cpu函数 编辑:程序博客网 时间:2024/05/21 10:47

    日常生活中,很多人都不知道自己的IP地址是多少,下面我来分享给大家一个获取本机的真实IP地址的方法,代码如下:

  1. import java.net.InetAddress;
  2. import java.net.NetworkInterface;
  3. import java.net.SocketException;
  4. import java.util.Enumeration;
  5. public class Main {
  6.     public static void main(String[] args) throws SocketException {
  7.         System.out.println(Main.getRealIp());
  8.     }
  9.     public static String getRealIp() throws SocketException {
  10.         String localip = null;// 本地IP,如果没有配置外网IP则返回它
  11.         String netip = null;// 外网IP
  12.         Enumeration<NetworkInterface> netInterfaces = 
  13.             NetworkInterface.getNetworkInterfaces();
  14.         InetAddress ip = null;
  15.         boolean finded = false;// 是否找到外网IP
  16.         while (netInterfaces.hasMoreElements() && !finded) {
  17.           NetworkInterface ni = netInterfaces.nextElement();
  18.       Enumeration<InetAddress> address = ni.getInetAddresses();
  19.             while (address.hasMoreElements()) {
  20.                 ip = address.nextElement();
  21.               if (!ip.isSiteLocalAddress() 
  22.                         && !ip.isLoopbackAddress() 
  23.                         && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
  24.                     netip = ip.getHostAddress();
  25.                     finded = true;
  26.                               break;
  27.             } else if (ip.isSiteLocalAddress() 
  28.                      && !ip.isLoopbackAddress() 
  29.              && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
  30.                     localip = ip.getHostAddress();
  31.                 }
  32.             }
  33.         }
  34.         if (netip != null && !"".equals(netip)) {
  35.             return netip;
  36.         } else {
  37.             return localip;
  38.         }
  39.     }
  40. }
0 0
原创粉丝点击