Asp.Net MVC 3:客户端IP地址使用Javascript

时间:2012-07-19 06:22:47

标签: javascript jquery asp.net-mvc-3

  

可能重复:
  Get Client IP using just Javascript?

我正在开发.net mvc 3 应用程序。我只想获取客户端的IP地址。 如何使用 JavaScript 获取客户端IP。如果有人知道请分享。

3 个答案:

答案 0 :(得分:3)

你不能用javascript做到这一点。您可以使用javascript向控制器操作发送AJAX请求,该操作将返回从Request.UserHostAddress读取客户端的IP:

public ActionResult GetIP()
{
    return Json(new { ip = Request.UserHostAddress }, JsonRequestBehavior.AllowGet);
}

然后:

var url = '@Url.Action("GetIP", "SomeController")';
$.getJSON(url, function(result) {
    alert(result.ip);
});

答案 1 :(得分:0)

<html xmlns="http://www.w3.org/1999/xhtml">
              <head>
              <title></title>
              <script type="text/javascript">
                  window.onload = function () {
                      var script = document.createElement("script");
                      script.type = "text/javascript";
                      script.src = "http://jsonip.appspot.com/?callback=DisplayIP";
                      document.getElementsByTagName("head")[0].appendChild(script);
                  };
                  function DisplayIP(response) {
                      document.getElementById("ipaddress").innerHTML = "Your IP Address is " + response.ip;
                  }
              </script>
              </head>
              <body>
                  <form>
                      <span id = "ipaddress"></span>
                  </form>
              </body>
              </html>

答案 2 :(得分:0)

<!-- Require jQuery / Anyversion --><script type="text/javascript"  language="Javascript"    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- Require EasyJQuery After JQuery --><script type="text/javascript"     language="Javascript" src="http://api.easyjquery.com/easyjquery.js"></script>
<script type="text/javascript" language="Javascript">
// 1. Your Data Here
function my_callback(json) {
    alert("IP :" + json.IP + " nCOUNTRY: " + json.COUNTRY);
}

function my_callback2(json) {
    // more information at http://api.easyjquery.com/test/demo-ip.php
    alert("IP :" + json.IP + " nCOUNTRY: " + json.COUNTRY + " City: " + json.cityName + " regionName: " + json.regionName);
}

  // 2. Setup Callback Function
  // EasyjQuery_Get_IP("my_callback"); // fastest version
 EasyjQuery_Get_IP("my_callback2","full"); // full version
</script>​

a working Example