🌷🍁 博主 libin9iOak带您 Go to New World.✨🍁 🦄 个人主页——libin9iOak的博客🎐 🐳 《面试题大全》 文章图文并茂🦕生动形象🦖简单易学!欢迎大家来踩踩~🌺 🌊 《IDEA开发秘籍》学会IDEA常用操作,工作效率翻倍~💐 🪁🍁 希望本文能够给您带来一定的帮助🌸文章粗浅,敬请批评指正!🍁🐥
本文将讨论如何使用Java编程语言实现限制特定IP地址访问网页的功能。IP地址限制是一种常见的安全措施,用于限制只有特定IP地址的用户才能访问敏感页面或资源。通过在Java Web应用程序中实现IP地址过滤,可以增加系统的安全性。
在网络应用程序开发中,安全性是至关重要的。有时候,您可能需要限制对某些页面或资源的访问,以确保只有授权的用户才能获取这些敏感信息。IP地址限制是一种简单且有效的方法,允许您基于用户的IP地址来控制他们是否可以访问特定页面。本文将介绍如何使用Java编程语言实现IP地址限制功能。
要实现IP地址限制功能,您可以按照以下步骤进行操作:
HttpServletRequest
对象获取用户的IP地址。
web.xml
文件中配置过滤器映射,以便在特定URL上应用过滤器。
//最简单的获取外网ip的方法。可以直接用,但是没啥用..
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script>
document.write(returnCitySN["cip"]);
</script>
//最简单的获取外网ip的方法。可以直接用,但是没啥用..``<script src=``"http://pv.sohu.com/cityjson?ie=utf-8"``></script>``<script>`` ``document.write(returnCitySN[``"cip"``]);``</script>
JS获取内网Ip的方法://有些浏览器获取到的加密ip段有问题,所以当其时期
function getIP(callback) {
let recode = {};
let RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
// 如果不存在则使用一个iframe绕过
if (!RTCPeerConnection) {
// 因为这里用到了iframe,所以在调用这个方法的script上必须有一个iframe标签
// <iframe id="iframe" sandbox="allow-same-origin" style="display:none;"></iframe>
let win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection;
}
//创建实例,生成连接
let pc = new RTCPeerConnection();
// 匹配字符串中符合ip地址的字段
function handleCandidate(candidate) {
debugger;
let ip_regexp = /([0-9]{1,3}(\.[0-9]{1,3}){3}|([a-f0-9]{1,4}((:[a-f0-9]{1,4}){7}|:+[a-f0-9]{1,4}){6}))/;
let ip_isMatch = candidate.match(ip_regexp)[1];
if (!recode[ip_isMatch]) {
callback(ip_isMatch);
recode[ip_isMatch] = true;
}
}
//监听icecandidate事件
pc.onicecandidate = (ice) => {
if (ice.candidate) {
handleCandidate(ice.candidate.candidate);
}
};
//建立一个伪数据的通道
pc.createDataChannel('');
pc.createOffer((res) => {
pc.setLocalDescription(res);
}, () => {});
//延迟,让一切都能完成
setTimeout(() => {
let lines = pc.localDescription.sdp.split('\n');
lines.forEach(item => {
if (item.indexOf('a=candidate:') === 0) {
handleCandidate(item);
}
})
}, 1000);
}
getIP(function (ip) { alert(ip); });
利用WebRTC获取真实内网Ip,WebRTC是一个支持网页浏览器进行实时语音对话或视频对话的API
由于WebRTC在建立连接过程中,会向对方发送本地地址SDP,因此可以通过访问SDP获得访问者的IP
但是有些浏览器用不了,所以还是放弃这种方式了。
最后还是觉得用Java来实现比较好吧,前端文章页写个ajax,每次进入文章先判断文章是否需要限制IP访问,如果需要就请求下后端,后端获取Ip判断是否在白名单内。注意ajax要用同步。
Java获取访问者Ip方法:
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
System.out.println(ip);
完整代码
/**
* 判断文章是否有权可看
*
* @param map
* @return
*/
@RequestMapping("/isIntranet.do")
@ResponseBody
public String isIntranet(ServletRequest request, ServletResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
// 判断访问者Ip是否白名单内
boolean flag = isIPOK(req, resp);
System.out.println(flag);
if (flag) {
return "true";
} else {
return "false";
}
}
private boolean isIPOK(HttpServletRequest request, HttpServletResponse response) {
// String accessIP = IPUtil.getUserIp(request);
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
System.out.println(ip);
return isLAN(ip);
}
// 是否为内网网段
public boolean isLAN(String ip) {
if ("127.0.0.1".equals(ip)) {
return true;
}
boolean result = true;
try {
Properties prop = new Properties();
//获取设置Ip段的配置文件
InputStream in = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties");
prop.load(in);
// 遍历取值
Set<Object> objects = prop.keySet();
for (Object object : objects) {
String ipNot = new String(prop.getProperty((String)object).getBytes("iso-8859-1"), "gbk");
System.out.println(ipNot);
/*result = ipIsValid("192.168.8.78-192.168.255.255", ip) || ipIsValid("172.16.0.0-172.31.255.255", ip)
|| ipIsValid("10.0.0.0-10.255.255.255", ip);*/
result = ipIsValid(ipNot, ip);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
//校验Ip是否包含在Ip段内
public static boolean ipIsValid(String ipSection, String ip) {
if (ipSection == null) {
throw new NullPointerException("IP段不能为空!");
}
if (ip == null) {
throw new NullPointerException("IP不能为空!");
}
ipSection = ipSection.trim();
ip = ip.trim();
final String REGX_IP =
"((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
final String REGX_IPB = REGX_IP + "\\-" + REGX_IP;
if (!ipSection.matches(REGX_IPB) || !ip.matches(REGX_IP)) {
return false;
}
int idx = ipSection.indexOf('-');
idx = idx < 0 ? ipSection.length() : idx;
String[] sips = ipSection.substring(0, idx).split("\\.");
String[] sipe = ipSection.substring(idx + 1).split("\\.");
String[] sipt = ip.split("\\.");
long ips = 0L, ipe = 0L, ipt = 0L;
for (int i = 0; i < 4; ++i) {
ips = ips << 8 | Integer.parseInt(sips[i]);
ipe = ipe << 8 | Integer.parseInt(sipe[i]);
ipt = ipt << 8 | Integer.parseInt(sipt[i]);
}
if (ips > ipe) {
long t = ips;
ips = ipe;
ipe = t;
}
return ips <= ipt && ipt <= ipe;
}
以上方法均来自网络,亲测有效,记录于此。
通过实现IP地址限制功能,您可以有效地加强您的Web应用程序的安全性。这种方法特别适用于需要限制对敏感信息的访问的情况。通过在Java Web应用程序中实施IP地址限制,您可以降低未经授权用户访问敏感数据的风险。
限制IP地址访问页面是一种常见的安全措施,可以通过Java编程语言在Web应用程序中实现。本文介绍了实现IP地址限制的一般步骤,包括获取客户端IP地址、定义允许访问的IP地址列表、验证IP地址和实现过滤器或拦截器。
以下是一些可能有用的参考资料,可以帮助您深入了解和实施IP地址限制功能:
HttpServletRequest
请注意,实际实现可能会因您所使用的Java Web框架和具体需求而有所不同。在实际应用中,请始终考虑最佳的安全实践。
如果这篇文章对您有所帮助,或者有所启发的话,求一键三连:点赞、转发、收藏,您的支持是我坚持写作最大的动力。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有