Java获取IP等网络信息

ref:https://blog.csdn.net/nianbingsihan/article/details/80265029

在Linux 和 win 下 通用的 获取IP等网络信息,就用如下方式:

NetworkInterface可以通过getNetworkInterfaces方法来枚举本机所有的网络接口。
我们也可以利用getNetworkInterfaces得到的网络接口,来枚举与每一个网络接口 绑定的所有IP地址。

getInetAddresses方法
NetworkInterface 类可以通过getInetAddresse 方法以InetAddress 对象的形式返回和网络接口绑定的所有IP 地址。getInetAddresses 方法的定义如下:
public Enumeration<InetAddress> getInetAddresses()

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author liangqi
 * @date 2021/6/29 0:11
 */
public class NetDemo {

    public static void main(String[] args) throws Exception {
        System.out.println("本机IP:" + getIpAddress());

    }

    public static String getIpAddress() {
        String hostname = "eth0";

        try {
            //获取所有的网络接口
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                //遍历每一个网络接口
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                //若是网路接口是:1回环接口 2虚拟网口 3网口状态为unUser,则跳过
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    //返回和网络接口绑定的所有ip地址
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    String name = netInterface.getName();
                    System.out.println("网口名称:" + name);
                    while (addresses.hasMoreElements()) {
                        //遍历获取每一个IP地址
                        InetAddress inetAddress = addresses.nextElement();
                        System.out.println("inetAddress.getHostAddress(): " + inetAddress.getHostAddress());
                        if (inetAddress != null && inetAddress instanceof Inet4Address) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("IP地址获取失败" + e.toString());
        }
        return "";
    }


 
}

如果是在windows环境: 使用InetAddress.getLocalHost()方法即可…在linux下 下面的获取IP的方式有时候会不准确。想要准确使用上面方式。

import java.net.InetAddress;
 
public class Main {
   public static void main(String[] args) 
   throws Exception {
      InetAddress addr = InetAddress.getLocalHost();
      System.out.println("Local HostAddress: 
      "+addr.getHostAddress());
      String hostname = addr.getHostName();
      System.out.println("Local host name: "+hostname);
   }
}

代码运行结果:

Local HostAddress: 192.168.42.2
Local host name: f19ca2b695da
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值