使用Java获取发送请求的电脑的IP地址

    xiaoxiao2024-11-04  76

    获取发送请求的电脑的IP地址,并返回json格式数据。

    package com.ssm.controller; import net.sf.json.JSON; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; @Controller @CrossOrigin @RequestMapping(value = "GetIP") public class IPController { @ResponseBody @RequestMapping(value = "ip") public JSON getIP(HttpServletRequest request, HttpServletResponse response) { 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)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } //构建json Map map = new HashMap(); map.put("IP",ip); JSONObject jsonObject = JSONObject.fromObject(map); return jsonObject; } }

     

    最新回复(0)