Java后台获取客户端ip与服务器ip的方法

一、获取客户端ip的方法

    //传入request对象,获得客户端ip
    //注意,本地不行,本地会获取到0:0:0:0:0:0:0:1;服务器上是正常的
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		    //本地会获取到0:0:0:0:0:0:0:1
			ip = request.getRemoteAddr();
		}
		if (ip.contains(",")) {
			return ip.split(",")[0];
		} else {
			return ip;
		}
	}

二、获取服务器ip的方法

	public static String getServerIP() {
		String ip = null;
		try {
			//获取当前服务器ip
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			LOG.error("获取当前服务器ip报错", e);
		}
		return ip;
	}

三、其它备注

1.可以用RestTemplate发送http请求

import org.springframework.web.client.RestTemplate;

				RestTemplate restTemplate = new RestTemplate();
				//这个是发送get请求,然后把返回报文转为string类型
				String htmlXml = restTemplate.getForObject("www.baidu.com", String.class);

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