java获取项目所在服务器的ip地址和端口号(获取当前ip地址)

  • 一、不传参数
  • 二、通过 HttpServletRequest 获取
  • 三、配置文件获取
  • 四、ManagementFactory
  • 五、RequestContextHolder

1、不传参数,直接通过ServletRequestAttributes获取当前项目所在服务器的端口号和ip地址

public static String getUrl(){    
	ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();    
	HttpServletRequest request = requestAttributes.getRequest();    
	String localAddr = request.getLocalAddr();    
	int serverPort = request.getServerPort();    
	return "http://"+localAddr +":"+ serverPort;
}

2、通过 HttpServletRequest 传参数获取当前项目所在服务器的端口号和ip地址

//获取本地服务器的ip地址和端口号    
public static String getHttpUrl(HttpServletRequest request){        
	String localAddr = request.getLocalAddr();        
	int serverPort = request.getServerPort();        
	return "http://"+localAddr +":"+ serverPort;    
}

3、Java获取当前系统的ip地址,端口号从配置文件读取

@Value("${server.port}")
private int serverPort; 
public String getUrl() {    
	InetAddress address = null;    
	try {        
		address = InetAddress.getLocalHost();    
	} catch (UnknownHostException e) {        
		e.printStackTrace();    
	}    
	return "http://"+address.getHostAddress() +":"+this.serverPort;
}

4、tomcat服务器启动到时候获取服务器的ip和端口号,本方法在windows系统没问题,再Linux系统就不行了

 //获取本地服务器的ip地址和端口号
public static String getUrl() 
{        
	String serverIp = "";        
	String serverPort = "";        
	try {            
		MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();            
		Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),             Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));            
		serverIp = InetAddress.getLocalHost().getHostAddress();            
		serverPort = objectNames.iterator().next().getKeyProperty("port");        
	} catch (Exception e) {            
		e.printStackTrace();        
	}        
	String ipAndPost = "http://" + serverIp + serverPort;        return ipAndPost;    
}

5、获取服务器的ip+端口号

public static String PathAddress() {		
	String strResult = "";		
	HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder				.getRequestAttributes()).getRequest(); 		
	StringBuffer strBuf = new StringBuffer();	strBuf.append(request.getScheme() + "://");		
	strBuf.append(request.getServerName() + ":");		
	strBuf.append(request.getServerPort() + "");		
	strBuf.append(request.getContextPath() + "/");		
	strResult = strBuf.toString();
	// +"FHADMINM/";//加入项目的名称		
	return strResult;	
}

你可能感兴趣的:(Java,java,服务器,tcp/ip)