Java 获取ip地址和网络接口

栏目: Java · 发布时间: 8年前

内容简介:Java 获取ip地址和网络接口

网络相关对象在java.net包中。

1.获取主机对象InetAddress

//获取本地主机对象
InetAddress host = InetAddress.getLocalHost();

//根据ip地址或主机名获取主机对象,以主机名获取主机时需要DNS解析
InetAddress host = InetAddress.getByName("192.168.100.124");
InetAddress host = InetAddress.getByName("www.baidu.com");

2.获取主机对象的ip地址和主机名(需要dns解析主机名)

host.getHostAddress();
host.getHostName();

3.获取本机所有接口NetworkInterface并遍历

//返回数据类型为Enumeration
Enumeration<NetworkInterface> enu = NetworkInterface.getNetworkInterfaces();
while(enu.hasMoreElements){
    NetworkInterface inet = enu.nextElement();
    String intName = inet.getName();
}

由于一个接口上可能有多个子接口(辅助ip,如eth0:1),因此根据某个接口,可以得到该接口的所有ip地址枚举集合(同时包括Ipv4和ipv6接口)。

Enumeration<InetAddress> net_list = inet.getInetAddresses();
while(net_list.hasMoreElements){
    InetAddress net = net_list.nextElement();
    String ip = net.getHostAddress();
}

可以使用Collections.list()方法将Enumeration类型转换为ArrayList集合的数据结构,然后使用Itreator遍历器遍历。

以下是获取本机所有接口名称和这些接口上的ipv4地址的方法(适用于Windows和Linux)。

import java.net.*;
import java.util.*;

public class EnumDemo {
    public static void main(String[] args) {
        try {
            //获取所有接口,并放进枚举集合中,然后使用Collections.list()将枚举集合转换为ArrayList集合
            Enumeration<NetworkInterface> enu = NetworkInterface.getNetworkInterfaces();
            ArrayList<NetworkInterface> arr = Collections.list(enu);
            for(Iterator<NetworkInterface> it = arr.iterator();it.hasNext();) {
                NetworkInterface ni = it.next();
                String intName = ni.getName();   //获取接口名
                //获取每个接口中的所有ip网络接口集合,因为可能有子接口
                ArrayList<InetAddress> inets = Collections.list(ni.getInetAddresses());
                for(Iterator<InetAddress> it1 = inets.iterator();it1.hasNext();) {
                    InetAddress inet = it1.next();
                    //只筛选ipv4地址,否则会同时得到Ipv6地址
                    if(inet instanceof Inet4Address) {
                        String ip = inet.getHostAddress();
                        System.out.printf("%-10s %-5s %-6s %-15s\n", "InetfaceName:",intName,"| IPv4:",ip);
                    }
                }
            }
        } catch (SocketException s) {
            s.printStackTrace();
        }
    }
}

本文永久更新链接地址 http://www.linuxidc.com/Linux/2018-01/150197.htm


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

PHP Cookbook

PHP Cookbook

Adam Trachtenberg、David Sklar / O'Reilly Media / 2006-08-01 / USD 44.99

When it comes to creating dynamic web sites, the open source PHP language is red-hot property: used on more than 20 million web sites today, PHP is now more popular than Microsoft's ASP.NET technology......一起来看看 《PHP Cookbook》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具