Created
May 11, 2026 09:43
-
-
Save HydrangeaPurple/80b45dd247732bb3bbc1a5d5e9231746 to your computer and use it in GitHub Desktop.
java获取ip和端口号
This file contains hidden or 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
| import org.springframework.beans.BeansException; | |
| import org.springframework.core.env.Environment; | |
| import javax.management.MBeanServer; | |
| import javax.management.ObjectName; | |
| import javax.management.Query; | |
| import javax.servlet.http.HttpServletRequest; | |
| import java.lang.management.ManagementFactory; | |
| import java.net.Inet4Address; | |
| import java.net.InetAddress; | |
| import java.net.NetworkInterface; | |
| import java.net.SocketException; | |
| import java.util.Collections; | |
| import java.util.List; | |
| import java.util.Set; | |
| /** | |
| * 获取ip和端口号 | |
| */ | |
| public class IpAndPortUtils { | |
| private IpAndPortUtils() { | |
| } | |
| public static String getLocalIp() { | |
| String preferredIf = System.getProperty("dubbo.network.interface.preferred"); | |
| try { | |
| List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); | |
| // 1. 优先指定网卡 | |
| if (preferredIf != null && !preferredIf.isEmpty()) { | |
| for (NetworkInterface ni : interfaces) { | |
| if (preferredIf.equals(ni.getName())) { | |
| String ip = findIp(ni); | |
| if (ip != null) { | |
| return ip; | |
| } | |
| } | |
| } | |
| } | |
| // 2. 自动选择 | |
| String candidate = null; | |
| for (NetworkInterface ni : interfaces) { | |
| if (!ni.isUp() || ni.isLoopback() || ni.isVirtual()) { | |
| continue; | |
| } | |
| String name = ni.getName().toLowerCase(); | |
| if (name.startsWith("docker") || name.startsWith("br-") || name.startsWith("veth") || name.startsWith("cni") || name.startsWith("flannel") || name.startsWith("cali") || name.startsWith("virbr")) { | |
| continue; | |
| } | |
| for (InetAddress addr : Collections.list(ni.getInetAddresses())) { | |
| if (!(addr instanceof Inet4Address)) { | |
| continue; | |
| } | |
| if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isLinkLocalAddress()) { | |
| continue; | |
| } | |
| String ip = addr.getHostAddress(); | |
| // 优先返回私网IP | |
| if (isPrivateIp(ip)) { | |
| return ip; | |
| } | |
| // 记录候选 | |
| if (candidate == null) { | |
| candidate = ip; | |
| } | |
| } | |
| } | |
| return candidate; | |
| } catch (Exception ignored) { | |
| } | |
| return "127.0.0.1"; | |
| } | |
| private static String findIp(NetworkInterface ni) throws SocketException { | |
| String candidate = null; | |
| for (InetAddress addr : Collections.list(ni.getInetAddresses())) { | |
| // 仅 IPv4 | |
| if (!(addr instanceof Inet4Address)) { | |
| continue; | |
| } | |
| // 排除无效地址 | |
| if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isMulticastAddress()) { | |
| continue; | |
| } | |
| String ip = addr.getHostAddress(); | |
| // 优先返回 RFC1918 私网地址 | |
| if (isPrivateIp(ip)) { | |
| return ip; | |
| } | |
| // 保留第一个合法IP作为候选 | |
| if (candidate == null) { | |
| candidate = ip; | |
| } | |
| } | |
| return candidate; | |
| } | |
| private static boolean isPrivateIp(String ip) { | |
| return ip.startsWith("10.") || ip.startsWith("192.168.") || ip.matches("^172\\.(1[6-9]|2\\d|3[0-1])\\..*"); | |
| } | |
| /** | |
| * 通过Springboot环境获得端口 | |
| * | |
| * @return 端口 | |
| */ | |
| public static String getLocalPort() { | |
| String port = null; | |
| try { | |
| // 获取springboot的 | |
| Environment environment = SpringContextUtil.getBean(Environment.class); | |
| port = environment.getProperty("local.server.port"); | |
| if (ObjectIsNull.check(port)) { | |
| port = environment.getProperty("server.port"); | |
| } | |
| // 获取tomcat的 | |
| if (ObjectIsNull.check(port)) { | |
| try { | |
| MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); | |
| Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"))); | |
| port = objectNames.iterator().next().getKeyProperty("port"); | |
| } catch (Exception ignored) { | |
| } | |
| } | |
| } catch (BeansException ignored) { | |
| } | |
| return ObjectIsNull.check(port) ? "-1" : port; | |
| } | |
| /** | |
| * 获取ip:port | |
| * | |
| * @return 主机ip:端口 | |
| */ | |
| public static String getIpAndPort() { | |
| return getLocalIp() + ":" + getLocalPort(); | |
| } | |
| /** | |
| * 获取用户真实的IP地址 | |
| * | |
| * @return String | |
| */ | |
| public static String getUserIP(HttpServletRequest request) { | |
| // 优先取 X-Real-IP | |
| String ip = request.getHeader("X-Real-IP"); | |
| if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) { | |
| ip = request.getHeader("x-forwarded-for"); | |
| } | |
| if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) { | |
| ip = request.getRemoteAddr(); | |
| if ("0:0:0:0:0:0:0:1".equals(ip)) { | |
| ip = ""; | |
| } | |
| } | |
| if ("unknown".equalsIgnoreCase(ip)) { | |
| ip = ""; | |
| return ip; | |
| } | |
| int index = ip.indexOf(','); | |
| if (index >= 0) { | |
| ip = ip.substring(0, index); | |
| } | |
| return ip; | |
| } | |
| public static void main(String[] args) { | |
| System.out.println(getLocalIp()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment