ice world

There is nothing too difficult if you put your heart into it.
posts - 104, comments - 103, trackbacks - 0, articles - 0

Java获取本机IP列表

Posted on 2013-07-19 11:10 IceWee 阅读(4353) 评论(1)  编辑  收藏 所属分类: Java
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;
    }




Feedback

# re: Java获取本机IP列表  回复  更多评论   

2016-03-14 14:38 by 哈哈哈
必回

只有注册用户登录后才能发表评论。


网站导航: