Java常见问题汇总

来源: StackOverflow, 自己使用中总结

集合

并发

网络

获取本机IP

InetAddress inetAddress = InetAddress.getLocalHost();
String host = inetAddress.getHostAddress();
System.out.print("host is " + host + "\n");

结果: host is 127.0.0.1

在linux环境下,没法获取正确的ip地址,当然也有一部分人碰巧获取了正确的结果。实际上这个函数是按照host来查找ip地址的,在linux中这些地址在/etc/hosts文件中:

127.0.0.1 localhost
127.0.0.1 ubuntu
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

因此程序里也只是读取了该文件下的ip地址,用户的网络如果是静态ip的话,自己手动设置一下,也能返回正确的IP地址,但是这么做的确是很麻烦。还有一个方法就是,执行ifconfig,解析对应的结果。

或者使用NetworkInterface接口来获取:

public static String getHostIp() {
        Enumeration<NetworkInterface> netInterfaces = null;
        String host = "";
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                if(!ni.getName().isEmpty()) {
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        InetAddress inetAddress = ips.nextElement();
                        host = inetAddress.getHostAddress();
                        log.info("IP:" + host);
                        if(inetAddress.getHostAddress().matches("\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b")) {
                            return host;
                        }

                    }
                }
            }
        } catch (Exception e) {
            if(log.isInfoEnabled()) {
                log.info(e.getMessage());
            }
        }
        return host;
    }

其他

package-info.java作用

为标注在包上Annotation提供便利;
声明友好类和包常量;
提供包的整体注释说明。

示例说明:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值