Java获取本机IP列表的几种方法

1、Java获取本地IP地址方法网上搜一箩筐,但基本上都是获得一个IP,实际开发中一台电脑很可能有多个IP地址,如多网卡,或者安装了VM Ware虚拟机,就会虚拟出其他的网卡,那么传统的方法得到的一个IP地址就不全面了,下面贴出获取本机IP列表的方法:
/**
     * IceWee 2013.07.19
     * 获取本地IP列表(针对多网卡情况)
     *
     * 
@return
     
*/

     public  static List<String> getLocalIPList()  {
        List<String> ipList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) // IPV4
                        ip = inetAddress.getHostAddress();
                        ipList.add(ip);
                    }

                }

            }

        }
 catch (SocketException e) {
            e.printStackTrace();
        }

        return ipList;
    }


2、获取多网卡时的本机IP

  1. public String getLocalHostName() {  
  2.         String hostName;  
  3.         try {  
  4.             InetAddress addr = InetAddress.getLocalHost();  
  5.             hostName = addr.getHostName();  
  6.         } catch (Exception ex) {  
  7.             hostName = "";  
  8.         }  
  9.         return hostName;  
  10.     }  
  11.   
  12. public String[] getAllLocalHostIP() {  
  13.     String[] ret = null;  
  14.     try {  
  15.         String hostName = getLocalHostName();  
  16.         if (hostName.length() > 0) {  
  17.             InetAddress[] addrs = InetAddress.getAllByName(hostName);  
  18.             if (addrs.length > 0) {  
  19.                 ret = new String[addrs.length];  
  20.                 for (int i = 0; i < addrs.length; i++) {  
  21.                     ret[i] = addrs[i].getHostAddress();  
  22.                 }  
  23.             }  
  24.         }  
  25.   
  26.         } catch (Exception ex) {  
  27.             ret = null;  
  28.         }  
  29.         return ret;  
  30.     }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值