Java获取本地IP方法
2018-07-20 来源:open-open
获取本地服务器IP经常会出现127.0.0.1,0:0:0:0:0:0:0:1,fe80:0:0:0:960:74bd:e1a0:e5b9%11 这些情况,以下代码可解决此问题
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface
.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface networkInterface = enumeration.nextElement();
if (networkInterface.isUp()) {
Enumeration<InetAddress> addressEnumeration = networkInterface
.getInetAddresses();
while (addressEnumeration.hasMoreElements()) {
String ip = addressEnumeration.nextElement()
.getHostAddress();
final String REGX_IP = "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
if (ip.matches(REGX_IP) && !ip.equals("127.0.0.1")) {
System.out.println(ip);
}
}
}
}
} catch (Exception e) {
log.error("获取本机ip出现异常,异常信息为:" + e.getMessage());
}
}
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:C# Access数据库操作
下一篇: 基于消息机制的异步架构之消息队列
最新资讯
热门推荐