• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山高我为峰
博客园    首页    新随笔    联系   管理    订阅  订阅
java 获取本机的IP地址

方法一:这种方式有一定的局限性,在Linux下的执行结果是:本机的IP = xxx/127.0.1.1 (其中xxx是你的计算机名)

public void getLocalIPAddress() {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            String localIP = inetAddress.getHostAddress().trim();
            System.out.println(localIP);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
}

 

 

方法二:

private InetAddress getLocalIPAddress() {
        InetAddress ip = null;
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        return ip.getLocalHost();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

 

posted on 2015-12-04 14:58  山高我为峰  阅读(372)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3