rac*_*ana 7 html javascript java ip
我想在 javascript 中获取我机器的 Ip 地址,这在我的 html 页面中进一步引用。我已经参考了所有建议的链接,但没有得到任何答案。我不想使用任何链接来获取 IP,所以我尝试在我的 javascript 中使用以下代码行
var ip = '<%=request.getRemoteAddr();%>';
Run Code Online (Sandbox Code Playgroud)
或者
var ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
var ip = Request.UserHostAddress.ToString();
Run Code Online (Sandbox Code Playgroud)
但是没有得到结果。
请帮我找到解决方案。我想在我的 html 页面中包含这个 javascript,我不想使用任何链接来获取 IP。
All the links I have gone through gives the external links to get the IP address and I do not want to use any external link to get the IP.
鉴于从这里你可以做到这一点。
/**
* Get the user IP throught the webkitRTCPeerConnection
* @param onNewIP {Function} listener function to expose the IP locally
* @return undefined
*/
function getUserIP(onNewIP) { // onNewIp - your listener function for new IPs
//compatibility for firefox and chrome
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new myPeerConnection({
iceServers: []
}),
noop = function() {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
key;
function iterateIP(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
//create a bogus data channel
pc.createDataChannel("");
// create offer and set local description
pc.createOffer().then(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
}).catch(function(reason) {
// An error occurred, so handle the failure to connect
});
//listen for candidate events
pc.onicecandidate = function(ice) {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
// Usage
getUserIP(function(ip){
alert("Got IP! :" + ip);
});
Run Code Online (Sandbox Code Playgroud)
我认为 javascript 标准库中没有主机或 IP 地址的概念。所以你必须访问一些外部服务来为你查找主机名。
除非您可能想向服务器发送请求,该请求会返回主机 IP 地址!!
编辑
在 JSP 中,您可以使用HttpServletRequest 中的getRemoteHost()方法
获取用户的IP地址。
所以你可以写这样的东西 -
var ip = '<%=request.getRemoteHost();%>';
Run Code Online (Sandbox Code Playgroud)
^^ 上面这行是 JSP 代码,这应该是你从 java servlet 容器(如 tomcat)返回的 JSP 文件的一部分。这在静态 HTML 页面中不起作用。