我使用上面兩種方法都只會抓取到內網IP 哪一台電腦 例如:192.168.X.1 抓得到
可是外網訪客連接時,訪客的IP只會顯示我架站伺服器主機的IP,該從哪邊修正可以正確抓取訪客的IP呢?
補充:我覺得應該不是程式碼的問題,是否伺服器上要做什麼設定?
使用 VMware 安裝 作業系統:WINDOWS SERVER 2016
APE.NET MVC 開發的網站 使用 IIS發行網站
或許可朝透過javascript去存取client ip思考
https://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript
Samuel 是否在學校或公司這種有上百台電腦,要配合網管的設定呢?
最近網路上找的 剛好用到專案上
IIS
ASP.NET Web Forms C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string vClientIP = GetIPAddress();//取得ClientIP
Response.Write(vClientIP);
}
//Get Ip Address
protected string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
}
我這邊有一些取 ip 的方法給你參考,看有沒有你需要的
/// <summary>
/// 取得本機 IP Address
/// </summary>
/// <returns></returns>
public static List<string> GetHostIPAddress()
{
List<string> lstIPAddress = new List<string>();
IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ipa in IpEntry.AddressList)
{
if (ipa.AddressFamily == AddressFamily.InterNetwork)
lstIPAddress.Add(ipa.ToString());
}
return lstIPAddress;
}
/// <summary>
/// 取得遠端呼叫者ip
/// </summary>
/// <returns></returns>
public string GetClientIP()
{
string ClientIP = "";
if (Request.ServerVariables["HTTP_VIA"] == null)
{
ClientIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
}
else
{
ClientIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
ClientIP = ClientIP.Replace("::1", "127.0.0.1");
return ClientIP;
}
/// <summary>
/// 取得外網 IP Address
/// </summary>
/// <returns></returns>
public static string GetExtranetIPAddress()
{
HttpWebRequest request = HttpWebRequest.Create("http://www.whatismyip.com.tw") as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0";
string ip = string.Empty;
WebResponse response = request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string result = reader.ReadToEnd();
string pattern = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
ip = Regex.Match(result, pattern).ToString();
}
return ip;
}
我記得是對方安全性協定提昇的關係,可以加入此段程式碼
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
或是參考這篇文章
我把 HttpWebRequest request = HttpWebRequest.Create("http://ipinfo.io/ip") as HttpWebRequest;
做修改可以順利執行,可是取得的IP並不是客戶端的IP 而是 我伺服器的IP
Mars 我用手機網路連 會抓到 我架設網站伺服器主機上的 ipv4 預設閘道 與 DHCP伺服器 的IP (我伺服器ipv4 預設閘道 與 DHCP伺服器 是同一個IP)