Java获取本机ip地址

Windows查看本机ip地址:

  • Window + R打开,输入cmd打开cmd命令窗口。
  • 输入ipconfig后按回车。
    这里写图片描述

在程序中使用java获取本机ip地址代码如下:


import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

public final class IPUtil {

    private IPUtil() {}

    /**
     * 取到当前机器的IP地址
     * @return
     */
    public static String getIp() {
        String hostIp;
        List<String> ips = new ArrayList<>();
        Enumeration<NetworkInterface> netInterfaces;
        try {
            //返回此机器上的所有接口。
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            //测试此枚举是否包含更多的元素。
            while (netInterfaces.hasMoreElements()) {
                //返回此枚举的下一个元素。
                NetworkInterface netInterface = netInterfaces.nextElement();
                //返回一个具有绑定到此网络接口全部或部分 InetAddress 的 Enumeration。
                Enumeration<InetAddress> inetAddresses = netInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    //非本地环回接口 && IPV4
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        //返回 IP 地址字符串(以文本表现形式)。
                        ips.add(inetAddress.getHostAddress());
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        hostIp = collectionToDelimitedString(ips, ",");
        return hostIp;
    }

    private static String collectionToDelimitedString(Collection<String> coll, String delim) {
        if (coll == null || coll.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Iterator<?> it = coll.iterator();
        while (it.hasNext()) {
            sb.append(it.next());
            if (it.hasNext()) {
                sb.append(delim);
            }
        }
        return sb.toString();
    }

    /**
     * 获取主机名称
     * @return
     */
    public static String getHostName() {
        String hostName = null;
        try {
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hostName;
    }
    public static void main(String[] args) {
        System.out.println(IPUtil.getIp());
        System.out.println(IPUtil.getHostName());
    }
}

测试结果:
192.168.1.107
DESKTOP-OM1F3ML

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值