Ottenere l'indirizzo IP del server in ASP.NET?
Domanda
Come posso ottenere l'indirizzo IP del server che chiama la mia pagina ASP.NET? Ho visto cose su un oggetto Response, ma sono molto nuovo in c #. Grazie mille.
Soluzione
Questo dovrebbe funzionare:
//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
OPPURE
//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-visitatori-IP-address.html
Altri suggerimenti
Request.ServerVariables [" LOCAL_ADDR "];
Questo fornisce all'IP la richiesta per i server multi-homed
Quanto sopra è lento in quanto richiede una chiamata DNS (e ovviamente non funzionerà se non è disponibile). È possibile utilizzare il codice seguente per ottenere una mappa degli indirizzi IPV4 locali del PC corrente con la maschera di sottorete corrispondente:
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;
}
avviso: questo non è ancora implementato in 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();
}
Funzionerà con 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;
}