Skip to content

Commit

Permalink
获取本地Ip工具类
Browse files Browse the repository at this point in the history
  • Loading branch information
TreasureJade committed Dec 12, 2019
1 parent 1d0afea commit d58d3f8
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/main/java/com/swpu/uchain/blog/util/IpUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.swpu.uchain.blog.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
* @author hobo
* @description
*/
public class IpUtil {
public static String getHostIp() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress ip = (InetAddress) addresses.nextElement();
if (ip instanceof Inet4Address
//loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
&& !ip.isLoopbackAddress()
&& !ip.getHostAddress().contains(":")) {
return ip.getHostAddress() + ":8083";
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

0 comments on commit d58d3f8

Please sign in to comment.