Abrufen der IP-Adresse des Servers in ASP.NET?
Frage
Wie kann ich die IP-Adresse des Servers erhalten, die meine ASP.NET-Seite aufruft? Ich habe Sachen über ein Response-Objekt gesehen, aber ich bin sehr neu in c #. Dank einer Tonne.
Lösung
Dies sollte funktionieren:
//this gets the ip address of the server pc
public string GetIPAddress()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); // `Dns.Resolve()` method is deprecated.
IPAddress ipAddress = ipHostInfo.AddressList[0];
return ipAddress.ToString();
}
http: //wec-library.blogspot.com/2008/03/gets-ip-address-of-server-pc-using-c.html
oder
//while this gets the ip address of the visitor making the call
HttpContext.Current.Request.UserHostAddress;
http: //www.geekpedia. com / KB32_How-do-I-get-the-Besucher-IP-address.html
Andere Tipps
Request.ServerVariables["LOCAL_ADDR"];
Dies gibt die IP die Anfrage kam auf für Multi-Home-Server
Die oben ist langsam, da es einen DNS-Aufruf erfordert (und offensichtlich nicht funktionieren, wenn man nicht verfügbar ist). Sie können unter den Code verwenden, um eine Karte der aktuellen PC lokalen IPv4-Adressen mit den entsprechenden Subnetz-Maske zu bekommen:
public static Dictionary<IPAddress, IPAddress> GetAllNetworkInterfaceIpv4Addresses()
{
var map = new Dictionary<IPAddress, IPAddress>();
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (var uipi in ni.GetIPProperties().UnicastAddresses)
{
if (uipi.Address.AddressFamily != AddressFamily.InterNetwork) continue;
if (uipi.IPv4Mask == null) continue; //ignore 127.0.0.1
map[uipi.Address] = uipi.IPv4Mask;
}
}
return map;
}
Warnung: Die in Mono nicht implementiert ist noch
//this gets the ip address of the server pc
public string GetIPAddress()
{
string strHostName = System.Net.Dns.GetHostName();
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); <-- Obsolete
IPHostEntry ipHostInfo = Dns.GetHostEntry(strHostName);
IPAddress ipAddress = ipHostInfo.AddressList[0];
return ipAddress.ToString();
}
Dies wird für IPv4 arbeiten:
public static string GetServerIP()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress address in ipHostInfo.AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
return address.ToString();
}
return string.Empty;
}