Last active
April 9, 2021 06:54
-
-
Save HydrangeaPurple/29f2cb01bce957489a90295362568b73 to your computer and use it in GitHub Desktop.
java springboot 获取 ip 和端口
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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