java获取当前项目的ip和端口号
各位大佬不好意思,最近有点忙好久没更新了,今天来一篇就是我们常用的项目的ip和端口号的动态获取
ip动态获取:
public class IpUtil {
public static String getRemortIp(HttpServletRequest request){
if(request.getHeader("x-forwarded-for") == null){
return request.getRemoteAddr();
}
return request.getHeader("x-forwarded-for");
}
}
这里要注意下如果项目在我们本地的话这里获取到的IP为:
0:0:0:0:0:0:0:1
解决方法见下面链接:
https://blog.csdn.net/qq_34136709/article/details/106000178
个人建议如果在本地的话可以就直接设置成localhost,服务器上会获取得到特别在支付这一块用的比较多
端口动态获取:
public class PortUtil {
public static String getLocalPort() throws Exception {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objectNames = mBeanServer.queryNames(new ObjectName("*:type=Connector,*"), null);
if (objectNames == null || objectNames.size() <= 0) {
throw new IllegalStateException("Cannot get the names of MBeans controlled by the MBean server.");
}
for (ObjectName objectName : objectNames) {
String protocol = String.valueOf(mBeanServer.getAttribute(objectName, "protocol"));
String port = String.valueOf(mBeanServer.getAttribute(objectName, "port"));
// windows下属性名称为HTTP/1.1, linux下为org.apache.coyote.http11.Http11NioProtocol
if (protocol.equals("HTTP/1.1") || protocol.equals("org.apache.coyote.http11.Http11NioProtocol")) {
return port;
}
}
throw new IllegalStateException("Failed to get the HTTP port of the current server");
}
}
这里要注意区分下windows和linux系统中的protocol区别。
版权声明:本文为qq_34136709原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。