Obtenir l'adresse IP du serveur dans ASP.NET?
Question
Comment obtenir l'adresse IP du serveur qui appelle ma page ASP.NET? J'ai vu des choses sur un objet Response, mais je suis très nouveau en c #. Merci une tonne.
La solution
Cela devrait fonctionner:
//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
OU
//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-visiteurs-adresse-IP.html
Autres conseils
Request.ServerVariables [" LOCAL_ADDR &];];
Ceci donne l'adresse IP sur laquelle la requête est arrivée pour les serveurs multi-hébergés
La procédure ci-dessus est lente car elle nécessite un appel DNS (et ne fonctionnera évidemment pas si aucun n'est disponible). Vous pouvez utiliser le code ci-dessous pour obtenir une carte des adresses IPV4 locales du PC actuel avec leur masque de sous-réseau correspondant:
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;
}
avertissement: cela n'est pas encore implémenté dans Mono
//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();
}
Cela fonctionnera pour IPv4:
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;
}