servidor obtener nombre net cliente asp address c# ip-address ipv4

nombre - obtener ip del servidor c#



¿Cómo puedo determinar las direcciones IPv4 del host local? (10)

¿Cómo obtengo solo direcciones de Protocolo de Internet versión 4 de Dns.GetHostAddresses() ? Tengo el siguiente código y me da las direcciones IPv4 e IPv6. Tengo que hacer que funcione con cuadros que tienen varias direcciones IPv4.

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName()); private void get_IPs() { foreach (IPAddress a in localIPs) { server_ip = server_ip + a.ToString() + "/"; } }


Agrega algo como esto a tu código

if( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork ) // IPv4 address


Aquí hay una función que uso:

public static string GetIP4Address() { string IP4Address = String.Empty; foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName())) { if (IPA.AddressFamily == AddressFamily.InterNetwork) { IP4Address = IPA.ToString(); break; } } return IP4Address; }

Como enumerable:

public static IEnumerable<string> GetIP4Addresses() { return Dns.GetHostAddresses(Dns.GetHostName()) .Where(IPA => IPA.AddressFamily == AddressFamily.InterNetwork) .Select(x => x.ToString()); }


De mi blog :

/// <summary> /// This utility function displays all the IP (v4, not v6) addresses of the local computer. /// </summary> public static void DisplayIPAddresses() { StringBuilder sb = new StringBuilder(); // Get a list of all network interfaces (usually one per network card, dialup, and VPN connection) NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface network in networkInterfaces) { // Read the IP configuration for each network IPInterfaceProperties properties = network.GetIPProperties(); // Each network interface may have multiple IP addresses foreach (IPAddressInformation address in properties.UnicastAddresses) { // We''re only interested in IPv4 addresses for now if (address.Address.AddressFamily != AddressFamily.InterNetwork) continue; // Ignore loopback addresses (e.g., 127.0.0.1) if (IPAddress.IsLoopback(address.Address)) continue; sb.AppendLine(address.Address.ToString() + " (" + network.Name + ")"); } } MessageBox.Show(sb.ToString()); }

En particular, no recomiendo Dns.GetHostAddresses(Dns.GetHostName()); , independientemente de lo popular que sea esa línea en varios artículos y blogs.


Desde MSDN en Dns.GetHostAddresses ,

Cuando se pasa una cadena vacía como nombre de host, este método devuelve las direcciones IPv4 del host local para todos los sistemas operativos excepto Windows Server 2003; para Windows Server 2003, se devuelven las direcciones IPv4 e IPv6 para el host local.

Las direcciones IPv6 se filtran de los resultados del método GetHostAddresses si la computadora local no tiene IPv6 instalado. Como resultado, es posible recuperar una instancia de IPAddress vacía si solo los resultados de IPv6 están disponibles para el hostNameOrAddress.parameter.

Por lo tanto, puedes usar esto para intentar analizarlo :

IPAddress.TryParse

a continuación, compruebe AddressFamily cuál

Devuelve System.Net.Sockets.AddressFamily.InterNetwork para IPv4 o System.Net.Sockets.AddressFamily.InterNetworkV6 para IPv6.

string input = "192.168.0.10"; IPAddress address; if (IPAddress.TryParse(input, out address)) { switch (address.AddressFamily) { case System.Net.Sockets.AddressFamily.InterNetwork: // we have IPv4 break; case System.Net.Sockets.AddressFamily.InterNetworkV6: // we have IPv6 break; default: // do something else break; } }


Escriba locaIPs.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)


Este es mi código. Y puede encontrarlo en muchas tarjetas LAN.

private string GetLocalIpAddress() { string localIpAddress = string.Empty; NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } IPv4InterfaceStatistics adapterStat = (nic).GetIPv4Statistics(); UnicastIPAddressInformationCollection uniCast = (nic).GetIPProperties().UnicastAddresses; if (uniCast != null) { foreach (UnicastIPAddressInformation uni in uniCast) { if (adapterStat.UnicastPacketsReceived > 0 && adapterStat.UnicastPacketsSent > 0 && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback) { if (uni.Address.AddressFamily == AddressFamily.InterNetwork) { localIpAddress = nic.GetIPProperties().UnicastAddresses[0].Address.ToString(); break; } } } } } return localIpAddress; }


Muy limpio y dulce al usar Linq

IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName()).Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToArray();


Para mí la solución más limpia sería:

public static string GetLocalIP() { string ipv4Address = String.Empty; foreach (IPAddress currentIPAddress in Dns.GetHostAddresses(Dns.GetHostName())) { if (currentIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ipv4Address = currentIPAddress.ToString(); break; } } return ipv4Address; }


Usé la respuesta que comenzó con

/// <summary> and it mostly worked: //for some reason Visual Studio 2010 did not understand AddressFamily.Inernetwork if (address.Address.AddressFamily != AddressFamily.InterNetwork)

Tuve que usar:

if(address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)

pero en realidad usé

if(!address.Address.AddressFamily.Equals(System.Net.Sockets.AddressFamily.InterNetwork))

Además, he añadido:

if (network.OperationalStatus != OperationalStatus.Up) continue;

Debido a que había algunas redes que no funcionaban y que nunca deberían haber estado allí, vi que estaban en el registro. --- Alvin


Utilizo este método auxiliar que devuelve la primera dirección IPV4 activa después de filtrar el IPV6 y Loopback una vez

public static IPAddress GetLocalIPAddress() { IPAddress result = null; IPHostEntry iphostentry = Dns.GetHostEntry(Dns.GetHostName()); IPAddress[] ipv4Address = Array.FindAll(iphostentry.AddressList, add => add.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(add)); if (ipv4Address.Length > 0 ) { result =ipv4Address[0]; } return result; }