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


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

查看所有标签

猜你喜欢:

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

Python Cookbook

Python Cookbook

Alex Martelli、Anna Ravenscroft、David Ascher / 高铁军 / 人民邮电出版社 / 2010-5-1 / 99.00元

本书介绍了Python应用在各个领域中的一些使用技巧和方法,从最基本的字符、文件序列、字典和排序,到进阶的面向对象编程、数据库和数据持久化、 XML处理和Web编程,再到比较高级和抽象的描述符、装饰器、元类、迭代器和生成器,均有涉及。书中还介绍了一些第三方包和库的使用,包括 Twisted、GIL、PyWin32等。本书覆盖了Python应用中的很多常见问题,并提出了通用的解决方案。书中的代码和方......一起来看看 《Python Cookbook》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

SHA 加密
SHA 加密

SHA 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具