Skip to content

Instantly share code, notes, and snippets.

@HydrangeaPurple
Last active April 9, 2021 06:54
Show Gist options
  • Save HydrangeaPurple/29f2cb01bce957489a90295362568b73 to your computer and use it in GitHub Desktop.
Save HydrangeaPurple/29f2cb01bce957489a90295362568b73 to your computer and use it in GitHub Desktop.
java springboot 获取 ip 和端口
package com.tydic.service.util;
import org.springframework.core.env.Environment;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* springboot获得ip和端口工具类
* @author chengyiqun
*/
public class IpAndPortUtils {
private IpAndPortUtils() { }
/**
* 获取ip
* @return ip
*/
public static String getLocalIp() {
String localIP = "127.0.0.1";
try {
OK:
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
continue;
}
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address instanceof Inet4Address) {
localIP = address.getHostAddress();
break OK;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return localIP;
}
/**
* 通过Springboot环境获得端口
* @return 端口
*/
public static String getLocalPort() {
Environment environment = SpringContextUtils.getBean(Environment.class);
return environment.getProperty("local.server.port");
}
/**
* 获取ip:port
* @return 主机ip:端口
*/
public static String getIpAndPort() {
return getLocalIp() + ":" + getLocalPort();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment