来源: 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提供便利;
声明友好类和包常量;
提供包的整体注释说明。
示例说明: