¿Obtener la dirección IP del servidor en ASP.NET?
Pregunta
¿Cómo obtengo la dirección IP del servidor que llama a mi página ASP.NET? He visto cosas sobre un objeto Response, pero soy muy nuevo en c #. Muchas gracias.
Solución
Esto debería funcionar:
//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
O
//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-Visitors-IP-address.html
Otros consejos
Request.ServerVariables["LOCAL_ADDR"font>;
Esto le da a la IP que entró la solicitud para servidores con múltiples hosts
Lo anterior es lento ya que requiere una llamada DNS (y obviamente no funcionará si no hay una disponible). Puede usar el siguiente código para obtener un mapa de las direcciones IPV4 locales de la PC actual con su máscara de subred correspondiente:
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;
}
advertencia: esto aún no está implementado en 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();
}
Esto funcionará para 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;
}