如何獲得公共IP地址,局域網IP地址&客戶機在MVC 4中的MAC地址?在MVC 4中獲取公共IP地址,客戶機的Lan IP地址和MAC地址?
我正在嘗試獲取客戶端計算機的IP地址。 Request.UserHostAddress
給出Lan IP地址,但是
- 全球IP地址呢?
- 如何獲取公共IP地址?
- 谷歌,whatismyip.com和其他許多網站如何選擇我們的公有IP地址等。
如何獲得公共IP地址,局域網IP地址&客戶機在MVC 4中的MAC地址?在MVC 4中獲取公共IP地址,客戶機的Lan IP地址和MAC地址?
我正在嘗試獲取客戶端計算機的IP地址。 Request.UserHostAddress
給出Lan IP地址,但是
對於LAN IP地址:
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
對於公共IP地址:
public static string GetPublicIP()
{
string url = "http://checkip.dyndns.org";
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
System.Net.WebResponse resp = req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string response = sr.ReadToEnd().Trim();
string[] a = response.Split(':');
string a2 = a[1].Substring(1);
string[] a3 = a2.Split('<');
string a4 = a3[0];
return a4;
}
或
private string GetPublicIpAddress()
{
var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");
request.UserAgent = "curl"; // this simulate curl linux command
string publicIPAddress;
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
publicIPAddress = reader.ReadToEnd();
}
}
return publicIPAddress.Replace("\n", "");
}
對於MAC地址:
public string GetMACAddress()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
} return sMacAddress;
}
試試這個,它可能對你有幫助。
如果您位於同一個Lan上,您只能獲得Lan IP地址。同樣,基於互聯網的服務只能看到公共IP地址,因爲您可以通過互聯網訪問它們。如果你在同一個網絡鏈路上,你只能看到MAC地址。您要求提供3種不同的信息,這些信息都在完全不同的級別上運行。你想要解決什麼實際問題? –
鑑於您的[評論](http://stackoverflow.com/questions/21751402/get-public-ip-address-lan-ip-address-mac-address-of-clients-machine-in-mvc-4#comment32901883_21751542 )詢問_「如何唯一標識訪問者?」_,我會說這是與[如何在ASP.NET應用程序中唯一標識客戶端機器?](http://stackoverflow.com/questions/4609316 /如何對唯一-識別最客戶機功能於一個-ASP淨應用程序)。 – CodeCaster