web-dev-qa-db-fra.com

Comment obtenir l'adresse IP du serveur sur lequel mon application C # s'exécute?

J'utilise un serveur et je veux afficher ma propre adresse IP.

Quelle est la syntaxe pour obtenir la propre adresse IP (si possible externe) de l'ordinateur?

Quelqu'un a écrit le code suivant.

IPHostEntry Host;
string localIP = "?";
Host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in Host.AddressList)
{
    if (ip.AddressFamily.ToString() == "InterNetwork")
    {
        localIP = ip.ToString();
    }
}
return localIP;

Cependant, je me méfie généralement de l'auteur et je ne comprends pas ce code. Y a-t-il une meilleure façon de le faire?

359
Nefzen

Non, c'est à peu près la meilleure façon de le faire. En tant que machine, pourrait avoir plusieurs adresses IP, vous devez en parcourir la collection pour trouver celle qui convient.

Edit: La seule chose que je voudrais changerais serait de changer ceci:

if (ip.AddressFamily.ToString() == "InterNetwork")

pour ça:

if (ip.AddressFamily == AddressFamily.InterNetwork)

Il n'est pas nécessaire de ToString une énumération à des fins de comparaison.

234
Andrew Hare

La seule façon de connaître votre adresse IP publique est de demander à quelqu'un d'autre de vous le dire. ce code peut vous aider:

public string GetPublicIP()
{
    String direction = "";
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
    using (WebResponse response = request.GetResponse())
    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
    {
        direction = stream.ReadToEnd();
    }

    //Search for the ip in the html
    int first = direction.IndexOf("Address: ") + 9;
    int last = direction.LastIndexOf("</body>");
    direction = direction.Substring(first, last - first);

    return direction;
}
163
ezgar

Nettoyant et une solution tout en un: D

//This returns the first IP4 address or null
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
81

Si vous ne pouvez pas compter sur l'obtention de votre adresse IP auprès d'un serveur DNS (ce qui m'est arrivé), vous pouvez utiliser l'approche suivante:

L'espace de noms System.Net.NetworkInformation contient une classe NetworkInterface , qui possède une méthode statique GetAllNetworkInterfaces .

Cette méthode renvoie toutes les "interfaces réseau" sur votre machine, et il en existe généralement plusieurs, même si vous ne disposez que d’un adaptateur sans fil et/ou d’un adaptateur Ethernet sur votre machine. Toutes ces interfaces réseau ont des adresses IP valides pour votre ordinateur local, bien que vous n'en souhaitiez probablement qu'une.

Si vous recherchez une adresse IP, vous devrez alors filtrer la liste jusqu'à ce que vous puissiez identifier la bonne adresse. Vous aurez probablement besoin d'expérimenter, mais j'ai eu du succès avec l'approche suivante:

  • Filtrez toutes les interfaces réseau inactives en recherchant OperationalStatus == OperationalStatus.Up. Cela exclura votre adaptateur Ethernet physique, par exemple, si vous n'avez pas de câble réseau branché.

Pour chaque interface réseau, vous pouvez obtenir un objet IPInterfaceProperties à l'aide de la méthode GetIPProperties et à partir d'un objet IPInterfaceProperties, vous pouvez accéder à la propriété UnicastAddresses pour obtenir la liste des objets UnicastIPAddressInformation .

  • Filtrer les adresses de monodiffusion non préférées en vérifiant DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
  • Filtrez les adresses "virtuelles" en vérifiant AddressPreferredLifetime != UInt32.MaxValue.

À ce stade, je prends l'adresse de la première adresse monodiffusion (le cas échéant) correspondant à tous ces filtres.

MODIFIER:

[code révisé du 16 mai 2018 pour inclure les conditions mentionnées dans le texte ci-dessus pour l'état de détection d'adresses en double et la durée de vie préférée]

L'exemple ci-dessous illustre le filtrage basé sur l'état opérationnel, la famille d'adresses, à l'exclusion de l'adresse de bouclage (127.0.0.1), de l'état de détection d'adresse en double et de la durée de vie préférée.

static IEnumerable<IPAddress> GetLocalIpAddresses()
{
    // Get the list of network interfaces for the local computer.
    var adapters = NetworkInterface.GetAllNetworkInterfaces();

    // Return the list of local IPv4 addresses excluding the local
    // Host, disconnected, and virtual addresses.
    return (from adapter in adapters
            let properties = adapter.GetIPProperties()
            from address in properties.UnicastAddresses
            where adapter.OperationalStatus == OperationalStatus.Up &&
                  address.Address.AddressFamily == AddressFamily.InterNetwork &&
                  !address.Equals(IPAddress.Loopback) &&
                  address.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred &&
                  address.AddressPreferredLifetime != UInt32.MaxValue
            select address.Address);
}
50
WebClient webClient = new WebClient();
string IP = webClient.DownloadString("http://myip.ozymo.com/");
37
James
using System.Net;

string Host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(Host);
Console.WriteLine(ip.AddressList[0].ToString());

Je viens de tester cela sur ma machine et cela fonctionne.

17
opedog

Si vous voulez éviter d'utiliser DNS:

List<IPAddress> ipList = new List<IPAddress>();
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
    foreach (var address in netInterface.GetIPProperties().UnicastAddresses)
    {
        if (address.Address.AddressFamily == AddressFamily.InterNetwork)
        {
            Console.WriteLine("found IP " + address.Address.ToString());
            ipList.Add(address.Address);
        }
    }
}
15
reza

Ne comptez pas tout le temps sur InterNetwork car vous pouvez avoir plusieurs périphériques qui utilisent également IP4, ce qui risquerait de fausser les résultats pour obtenir votre adresse IP . Maintenant, si vous le souhaitez, copiez-le et relisez-le. ou mettez-le à jour à votre guise.

Je reçois d’abord l’adresse du routeur (passerelle) S'il me revient que je suis connecté à une passerelle (c’est-à-dire qu’il n’est pas connecté directement au modem sans fil ou non), nous avons notre adresse de passerelle IPAddress, sinon nous avons la valeur null. pointeur IPAddress référence.

Ensuite, nous devons obtenir la liste d'adresses IP de l'ordinateur. C'est là que les choses ne sont pas si difficiles car les routeurs (tous les routeurs) utilisent 4 octets (...). Les trois premiers sont les plus importants, car l'adresse IP4 de tout ordinateur connecté à l'ordinateur correspond aux trois premiers octets. Ex: 192.168.0.1 est la norme pour l'IP par défaut du routeur, à moins que cela ne soit modifié par son administrateur. "192.168.0" ou ce qu'ils peuvent être est ce que nous devons faire correspondre. Et c'est tout ce que j'ai fait dans la fonction IsAddressOfGateway. La raison de la correspondance de longueur est due au fait que toutes les adresses (qui ne concernent que l’ordinateur) ont une longueur de 4 octets. Si vous tapez netstat dans la cmd, vous constaterez que cela est vrai. Donc là vous l'avez. Oui, il faut un peu plus de travail pour vraiment obtenir ce que vous recherchez. Processus d'élimination ... Et pour l'amour de Dieu, ne trouvez pas l'adresse en la cinglant, ce qui prend du temps, car vous envoyez d'abord l'adresse à cingler, puis le résultat doit être renvoyé. Non, travaillez directement avec les classes .Net qui traitent de votre environnement système et vous obtiendrez les réponses que vous recherchez quand il s'agit uniquement de votre ordinateur.

Maintenant, si vous êtes directement connecté à votre modem, le processus est presque identique car le modem est votre passerelle mais le sous-masque n’est pas identique car vous obtenez les informations directement à partir de votre serveur DNS via modem et non masquées par le routeur Si vous utilisez toujours le même code, utilisez Internet même si le dernier octet de l’adresse IP attribuée au modem est 1. Donc, si l’IP envoyé depuis le modem qui change est 111.111.111.1 ', vous obtiendrez alors 111.111.111. valeur d'octet). N'oubliez pas qu'il est nécessaire de trouver les informations relatives à la passerelle car il existe plus de périphériques prenant en charge la connectivité Internet que votre routeur et votre modem.

Vous voyez maintenant pourquoi vous ne changez pas les deux premiers octets 192 et 168 de votre routeur. Ils sont strictement réservés aux routeurs et non à Internet, sinon nous aurions un problème sérieux avec le protocole IP et un double ping provoquant un crash de votre ordinateur. Image indiquant que l'adresse IP de votre routeur attribué est 192.168.44.103 et que vous cliquez également sur un site ayant cette adresse IP. OMG! Votre ordinateur ne saura pas quoi faire. Crash juste là. Pour éviter ce problème, seuls les routeurs se voient attribuer ces informations, pas pour une utilisation Internet. Donc, laissez les deux premiers octets du routeur seul.

static IPAddress FindLanAddress()
{
    IPAddress gateway = FindGetGatewayAddress();
    if (gateway == null)
        return null;

    IPAddress[] pIPAddress = Dns.GetHostAddresses(Dns.GetHostName());

    foreach (IPAddress address in pIPAddress)            {
        if (IsAddressOfGateway(address, gateway))
                return address;
    return null;
}
static bool IsAddressOfGateway(IPAddress address, IPAddress gateway)
{
    if (address != null && gateway != null)
        return IsAddressOfGateway(address.GetAddressBytes(),gateway.GetAddressBytes());
    return false;
}
static bool IsAddressOfGateway(byte[] address, byte[] gateway)
{
    if (address != null && gateway != null)
    {
        int gwLen = gateway.Length;
        if (gwLen > 0)
        {
            if (address.Length == gateway.Length)
            {
                --gwLen;
                int counter = 0;
                for (int i = 0; i < gwLen; i++)
                {
                    if (address[i] == gateway[i])
                        ++counter;
                }
                return (counter == gwLen);
            }
        }
    }
    return false;

}
static IPAddress FindGetGatewayAddress()
{
    IPGlobalProperties ipGlobProps = IPGlobalProperties.GetIPGlobalProperties();

    foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
    {
        IPInterfaceProperties ipInfProps = ni.GetIPProperties();
        foreach (GatewayIPAddressInformation gi in ipInfProps.GatewayAddresses)
            return gi.Address;
    }
    return null;
}
9
bvrwoo_3376

Je pensais juste que j'ajouterais mon propre one-line (même s'il y a déjà beaucoup d'autres réponses utiles).


string ipAddress = new WebClient().DownloadString("http://icanhazip.com");

8
bæltazor

Pour obtenir l'adresse IP publique actuelle, il vous suffit de créer une page ASPX avec la ligne suivante dans l'événement de chargement de page:

Response.Write(HttpContext.Current.Request.UserHostAddress.ToString());

Si vous utilisez l'intranet, vous pourrez obtenir l'adresse IP de la machine locale. Sinon, vous obtiendrez une adresse IP externe avec ceci: Web:

//this will bring the IP for the current machine on browser
System.Web.HttpContext.Current.Request.UserHostAddress

Bureau:

//This one will bring all local IPs for the desired namespace
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
4
Guilherme Ferreira
namespace NKUtilities 
{
    using System;
    using System.Net;
    using System.Net.Sockets;

    public class DNSUtility
    {
        public static int Main(string [] args)
        {
            string strHostName = "";
            try {

                if(args.Length == 0)
                {
                    // Getting Ip address of local machine...
                    // First get the Host name of local machine.
                    strHostName = Dns.GetHostName();
                    Console.WriteLine ("Local Machine's Host Name: " +  strHostName);
                }
                else
                {
                    // Otherwise, get the IP address of the Host provided on the command line.
                    strHostName = args[0];
                }

                // Then using Host name, get the IP address list..
                IPHostEntry ipEntry = Dns.GetHostEntry (strHostName);
                IPAddress [] addr = ipEntry.AddressList;

                for(int i = 0; i < addr.Length; i++)
                {
                    Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
                }
                return 0;

            } 
            catch(SocketException se) 
            {
                Console.WriteLine("{0} ({1})", se.Message, strHostName);
                return -1;
            } 
            catch(Exception ex) 
            {
                Console.WriteLine("Error: {0}.", ex.Message);
                return -1;
            }
        }
    }
}

Regardez ici pour plus de détails.

Vous devez vous rappeler que votre ordinateur peut avoir plusieurs adresses IP (en fait, c'est toujours le cas).

3
mfloryan

Essaye ça:

 IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
 String MyIp = localIPs[0].ToString();
2
The Mask

Cela fonctionne pour moi ... et devrait être plus rapide dans la plupart des cas (sinon tous) que d'interroger un serveur DNS. Merci à l'apprenti du Dr. Wily ( ici ).

// ************************************************************************
/// <summary>
/// Will search for the an active NetworkInterafce that has a Gateway, otherwise
/// it will fallback to try from the DNS which is not safe.
/// </summary>
/// <returns></returns>
public static NetworkInterface GetMainNetworkInterface()
{
    List<NetworkInterface> candidates = new List<NetworkInterface>();

    if (NetworkInterface.GetIsNetworkAvailable())
    {
        NetworkInterface[] NetworkInterfaces =
            NetworkInterface.GetAllNetworkInterfaces();

        foreach (
            NetworkInterface ni in NetworkInterfaces)
        {
            if (ni.OperationalStatus == OperationalStatus.Up)
                candidates.Add(ni);
        }
    }

    if (candidates.Count == 1)
    {
        return candidates[0];
    }

    // Accoring to our tech, the main NetworkInterface should have a Gateway 
    // and it should be the ony one with a gateway.
    if (candidates.Count > 1)
    {
        for (int n = candidates.Count - 1; n >= 0; n--)
        {
            if (candidates[n].GetIPProperties().GatewayAddresses.Count == 0)
            {
                candidates.RemoveAt(n);
            }
        }

        if (candidates.Count == 1)
        {
            return candidates[0];
        }
    }

    // Fallback to try by getting my ipAdress from the dns
    IPAddress myMainIpAdress = null;
    IPHostEntry Host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (IPAddress ip in Host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork) // Get the first IpV4
        {
            myMainIpAdress = ip;
            break;
        }
    }

    if (myMainIpAdress != null)
    {
        NetworkInterface[] NetworkInterfaces =
            NetworkInterface.GetAllNetworkInterfaces();

        foreach (NetworkInterface ni in NetworkInterfaces)
        {
            if (ni.OperationalStatus == OperationalStatus.Up)
            {
                IPInterfaceProperties props = ni.GetIPProperties();
                foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
                {
                    if (ai.Address.Equals(myMainIpAdress))
                    {
                        return ni;
                    }
                }
            }
        }
    }

    return null;
}

// ******************************************************************
/// <summary>
/// AddressFamily.InterNetwork = IPv4
/// Thanks to Dr. Wilys Apprentice at
/// http://stackoverflow.com/questions/1069103/how-to-get-the-ip-address-of-the-server-on-which-my-c-sharp-application-is-runni
/// using System.Net.NetworkInformation;
/// </summary>
/// <param name="mac"></param>
/// <param name="addressFamily">AddressFamily.InterNetwork = IPv4,  AddressFamily.InterNetworkV6 = IPv6</param>
/// <returns></returns>
public static IPAddress GetIpFromMac(PhysicalAddress mac, AddressFamily addressFamily = AddressFamily.InterNetwork)
{
    NetworkInterface[] NetworkInterfaces =
        NetworkInterface.GetAllNetworkInterfaces();

    foreach (NetworkInterface ni in NetworkInterfaces)
    {
        if (ni.GetPhysicalAddress().Equals(mac))
        {
            if (ni.OperationalStatus == OperationalStatus.Up)
            {
                IPInterfaceProperties props = ni.GetIPProperties();
                foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
                {
                    if (ai.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)
                    {
                        if (ai.Address.AddressFamily == addressFamily)
                        {
                            return ai.Address;
                        }
                    }
                }
            }
        }
    }

    return null;
}

// ******************************************************************
/// <summary>
/// Return the best guess of main ipAdress. To get it in the form aaa.bbb.ccc.ddd just call 
/// '?.ToString() ?? ""' on the result.
/// </summary>
/// <returns></returns>
public static IPAddress GetMyInternetIpAddress()
{
    NetworkInterface ni = GetMainNetworkInterface();
    IPAddress ipAddress = GetIpFromMac(ni.GetPhysicalAddress());
    if (ipAddress == null) // could it be possible ?
    {
        ipAddress = GetIpFromMac(ni.GetPhysicalAddress(), AddressFamily.InterNetworkV6);
    }

    return ipAddress;
}

// ******************************************************************

Juste comme référence c'est le code de classe complet où je l'ai défini:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace TcpMonitor
{
    /*
        Usage:
                var cons = TcpHelper.GetAllTCPConnections();
                foreach (TcpHelper.MIB_TCPROW_OWNER_PID c in cons) ...
    */

    public class NetHelper
    {
        [DllImport("iphlpapi.dll", SetLastError = true)]
        static extern uint GetExtendedUdpTable(IntPtr pUdpTable, ref int dwOutBufLen, bool sort, int ipVersion, UDP_TABLE_CLASS tblClass, uint reserved = 0);

        public enum UDP_TABLE_CLASS
        {
            UDP_TABLE_BASIC,
            UDP_TABLE_OWNER_PID,
            UDP_TABLE_OWNER_MODULE
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MIB_UDPTABLE_OWNER_PID
        {
            public uint dwNumEntries;
            [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
            public MIB_UDPROW_OWNER_PID[] table;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MIB_UDPROW_OWNER_PID
        {
            public uint localAddr;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public byte[] localPort;
            public uint owningPid;

            public uint ProcessId
            {
                get { return owningPid; }
            }

            public IPAddress LocalAddress
            {
                get { return new IPAddress(localAddr); }
            }

            public ushort LocalPort
            {
                get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MIB_UDP6TABLE_OWNER_PID
        {
            public uint dwNumEntries;
            [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
            public MIB_UDP6ROW_OWNER_PID[] table;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MIB_UDP6ROW_OWNER_PID
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public byte[] localAddr;
            public uint localScopeId;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public byte[] localPort;
            public uint owningPid;
            public uint ProcessId
            {
                get { return owningPid; }
            }

            public IPAddress LocalAddress
            {
                get { return new IPAddress(localAddr, localScopeId); }
            }

            public ushort LocalPort
            {
                get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
            }
        }

        public static List<MIB_UDPROW_OWNER_PID> GetAllUDPConnections()
        {
            return GetUDPConnections<MIB_UDPROW_OWNER_PID, MIB_UDPTABLE_OWNER_PID> (AF_INET);
        }

        public static List<MIB_UDP6ROW_OWNER_PID> GetAllUDPv6Connections()
        {
            return GetUDPConnections<MIB_UDP6ROW_OWNER_PID, MIB_UDP6TABLE_OWNER_PID>(AF_INET6);
        }

        private static List<IPR> GetUDPConnections<IPR, IPT>(int ipVersion)//IPR = Row Type, IPT = Table Type
        {
            List<IPR> result = null;

            IPR[] tableRows = null;
            int buffSize = 0;

            var dwNumEntriesField = typeof(IPT).GetField("dwNumEntries");

            // how much memory do we need?
            uint ret = GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, ipVersion, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
            IntPtr udpTablePtr = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedUdpTable(udpTablePtr, ref buffSize, true, ipVersion, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
                if (ret != 0)
                    return new List<IPR>();

                // get the number of entries in the table
                IPT table = (IPT)Marshal.PtrToStructure(udpTablePtr, typeof(IPT));
                int rowStructSize = Marshal.SizeOf(typeof(IPR));
                uint numEntries = (uint)dwNumEntriesField.GetValue(table);

                // buffer we will be returning
                tableRows = new IPR[numEntries];

                IntPtr rowPtr = (IntPtr)((long)udpTablePtr + 4);
                for (int i = 0; i < numEntries; i++)
                {
                    IPR tcpRow = (IPR)Marshal.PtrToStructure(rowPtr, typeof(IPR));
                    tableRows[i] = tcpRow;
                    rowPtr = (IntPtr)((long)rowPtr + rowStructSize);   // next entry
                }
            }
            finally
            {
                result = tableRows?.ToList() ?? new List<IPR>();

                // Free the Memory
                Marshal.FreeHGlobal(udpTablePtr);
            }

            return result;
        }

        [DllImport("iphlpapi.dll", SetLastError = true)]
        static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort, int ipVersion, TCP_TABLE_CLASS tblClass, uint reserved = 0);



        public enum MIB_TCP_STATE
        {
            MIB_TCP_STATE_CLOSED = 1,
            MIB_TCP_STATE_LISTEN = 2,
            MIB_TCP_STATE_SYN_SENT = 3,
            MIB_TCP_STATE_SYN_RCVD = 4,
            MIB_TCP_STATE_ESTAB = 5,
            MIB_TCP_STATE_FIN_WAIT1 = 6,
            MIB_TCP_STATE_FIN_WAIT2 = 7,
            MIB_TCP_STATE_CLOSE_WAIT = 8,
            MIB_TCP_STATE_CLOSING = 9,
            MIB_TCP_STATE_LAST_ACK = 10,
            MIB_TCP_STATE_TIME_WAIT = 11,
            MIB_TCP_STATE_DELETE_TCB = 12
        }

        public enum TCP_TABLE_CLASS
        {
            TCP_TABLE_BASIC_LISTENER,
            TCP_TABLE_BASIC_CONNECTIONS,
            TCP_TABLE_BASIC_ALL,
            TCP_TABLE_OWNER_PID_LISTENER,
            TCP_TABLE_OWNER_PID_CONNECTIONS,
            TCP_TABLE_OWNER_PID_ALL,
            TCP_TABLE_OWNER_MODULE_LISTENER,
            TCP_TABLE_OWNER_MODULE_CONNECTIONS,
            TCP_TABLE_OWNER_MODULE_ALL
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MIB_TCPTABLE_OWNER_PID
        {
            public uint dwNumEntries;
            [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
            public MIB_TCPROW_OWNER_PID[] table;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MIB_TCP6TABLE_OWNER_PID
        {
            public uint dwNumEntries;
            [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
            public MIB_TCP6ROW_OWNER_PID[] table;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MIB_TCPROW_OWNER_PID
        {
            public uint state;
            public uint localAddr;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public byte[] localPort;
            public uint remoteAddr;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public byte[] remotePort;
            public uint owningPid;

            public uint ProcessId
            {
                get { return owningPid; }
            }

            public IPAddress LocalAddress
            {
                get { return new IPAddress(localAddr); }
            }

            public ushort LocalPort
            {
                get
                {
                    return BitConverter.ToUInt16(new byte[2] { localPort[1], localPort[0] }, 0);
                }
            }

            public IPAddress RemoteAddress
            {
                get { return new IPAddress(remoteAddr); }
            }

            public ushort RemotePort
            {
                get
                {
                    return BitConverter.ToUInt16(new byte[2] { remotePort[1], remotePort[0] }, 0);
                }
            }

            public MIB_TCP_STATE State
            {
                get { return (MIB_TCP_STATE)state; }
            }
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct MIB_TCP6ROW_OWNER_PID
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public byte[] localAddr;
            public uint localScopeId;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public byte[] localPort;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public byte[] remoteAddr;
            public uint remoteScopeId;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public byte[] remotePort;
            public uint state;
            public uint owningPid;

            public uint ProcessId
            {
                get { return owningPid; }
            }

            public long LocalScopeId
            {
                get { return localScopeId; }
            }

            public IPAddress LocalAddress
            {
                get { return new IPAddress(localAddr, LocalScopeId); }
            }

            public ushort LocalPort
            {
                get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
            }

            public long RemoteScopeId
            {
                get { return remoteScopeId; }
            }

            public IPAddress RemoteAddress
            {
                get { return new IPAddress(remoteAddr, RemoteScopeId); }
            }

            public ushort RemotePort
            {
                get { return BitConverter.ToUInt16(remotePort.Take(2).Reverse().ToArray(), 0); }
            }

            public MIB_TCP_STATE State
            {
                get { return (MIB_TCP_STATE)state; }
            }
        }


        public const int AF_INET = 2;    // IP_v4 = System.Net.Sockets.AddressFamily.InterNetwork
        public const int AF_INET6 = 23;  // IP_v6 = System.Net.Sockets.AddressFamily.InterNetworkV6

        public static Task<List<MIB_TCPROW_OWNER_PID>> GetAllTCPConnectionsAsync()
        {
            return Task.Run(() => GetTCPConnections<MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID>(AF_INET));
        }

        public static List<MIB_TCPROW_OWNER_PID> GetAllTCPConnections()
        {
            return GetTCPConnections<MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID>(AF_INET);
        }

        public static Task<List<MIB_TCP6ROW_OWNER_PID>> GetAllTCPv6ConnectionsAsync()
        {
            return Task.Run(()=>GetTCPConnections<MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID>(AF_INET6));
        }

        public static List<MIB_TCP6ROW_OWNER_PID> GetAllTCPv6Connections()
        {
            return GetTCPConnections<MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID>(AF_INET6);
        }

        private static List<IPR> GetTCPConnections<IPR, IPT>(int ipVersion)//IPR = Row Type, IPT = Table Type
        {
            List<IPR> result = null;

            IPR[] tableRows = null;
            int buffSize = 0;

            var dwNumEntriesField = typeof(IPT).GetField("dwNumEntries");

            // how much memory do we need?
            uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, ipVersion, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
            IntPtr tcpTablePtr = Marshal.AllocHGlobal(buffSize);

            try
            {
                ret = GetExtendedTcpTable(tcpTablePtr, ref buffSize, true, ipVersion, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                if (ret != 0)
                    return new List<IPR>();

                // get the number of entries in the table
                IPT table = (IPT)Marshal.PtrToStructure(tcpTablePtr, typeof(IPT));
                int rowStructSize = Marshal.SizeOf(typeof(IPR));
                uint numEntries = (uint)dwNumEntriesField.GetValue(table);

                // buffer we will be returning
                tableRows = new IPR[numEntries];

                IntPtr rowPtr = (IntPtr)((long)tcpTablePtr + 4);
                for (int i = 0; i < numEntries; i++)
                {
                    IPR tcpRow = (IPR)Marshal.PtrToStructure(rowPtr, typeof(IPR));
                    tableRows[i] = tcpRow;
                    rowPtr = (IntPtr)((long)rowPtr + rowStructSize);   // next entry
                }
            }
            finally
            {
                result = tableRows?.ToList() ?? new List<IPR>();

                // Free the Memory
                Marshal.FreeHGlobal(tcpTablePtr);
            }

            return result;
        }

        public static string GetTcpStateName(MIB_TCP_STATE state)
        {
            switch (state)
            {
                case MIB_TCP_STATE.MIB_TCP_STATE_CLOSED:
                    return "Closed";
                case MIB_TCP_STATE.MIB_TCP_STATE_LISTEN:
                    return "Listen";
                case MIB_TCP_STATE.MIB_TCP_STATE_SYN_SENT:
                    return "SynSent";
                case MIB_TCP_STATE.MIB_TCP_STATE_SYN_RCVD:
                    return "SynReceived";
                case MIB_TCP_STATE.MIB_TCP_STATE_ESTAB:
                    return "Established";
                case MIB_TCP_STATE.MIB_TCP_STATE_FIN_WAIT1:
                    return "FinWait 1";
                case MIB_TCP_STATE.MIB_TCP_STATE_FIN_WAIT2:
                    return "FinWait 2";
                case MIB_TCP_STATE.MIB_TCP_STATE_CLOSE_WAIT:
                    return "CloseWait";
                case MIB_TCP_STATE.MIB_TCP_STATE_CLOSING:
                    return "Closing";
                case MIB_TCP_STATE.MIB_TCP_STATE_LAST_ACK:
                    return "LastAck";
                case MIB_TCP_STATE.MIB_TCP_STATE_TIME_WAIT:
                    return "TimeWait";
                case MIB_TCP_STATE.MIB_TCP_STATE_DELETE_TCB:
                    return "DeleteTCB";
                default:
                    return ((int)state).ToString();
            }
        }

        private static readonly ConcurrentDictionary<string, string> DicOfIpToHostName = new ConcurrentDictionary<string, string>();

        public const string UnknownHostName = "Unknown";

        // ******************************************************************
        public static string GetHostName(IPAddress ipAddress)
        {
            return GetHostName(ipAddress.ToString());
        }

        // ******************************************************************
        public static string GetHostName(string ipAddress)
        {
            string hostName = null;

            if (!DicOfIpToHostName.TryGetValue(ipAddress, out hostName))
            {
                try
                {
                    if (ipAddress == "0.0.0.0" || ipAddress == "::")
                    {
                        hostName = ipAddress;
                    }
                    else
                    {
                        hostName = Dns.GetHostEntry(ipAddress).HostName;
                    }
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.ToString());
                    hostName = UnknownHostName;
                }

                DicOfIpToHostName[ipAddress] = hostName;
            }

            return hostName;
        }

        // ************************************************************************
        /// <summary>
        /// Will search for the an active NetworkInterafce that has a Gateway, otherwise
        /// it will fallback to try from the DNS which is not safe.
        /// </summary>
        /// <returns></returns>
        public static NetworkInterface GetMainNetworkInterface()
        {
            List<NetworkInterface> candidates = new List<NetworkInterface>();

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                NetworkInterface[] NetworkInterfaces =
                    NetworkInterface.GetAllNetworkInterfaces();

                foreach (
                    NetworkInterface ni in NetworkInterfaces)
                {
                    if (ni.OperationalStatus == OperationalStatus.Up)
                        candidates.Add(ni);
                }
            }

            if (candidates.Count == 1)
            {
                return candidates[0];
            }

            // Accoring to our tech, the main NetworkInterface should have a Gateway 
            // and it should be the ony one with a gateway.
            if (candidates.Count > 1)
            {
                for (int n = candidates.Count - 1; n >= 0; n--)
                {
                    if (candidates[n].GetIPProperties().GatewayAddresses.Count == 0)
                    {
                        candidates.RemoveAt(n);
                    }
                }

                if (candidates.Count == 1)
                {
                    return candidates[0];
                }
            }

            // Fallback to try by getting my ipAdress from the dns
            IPAddress myMainIpAdress = null;
            IPHostEntry Host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in Host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork) // Get the first IpV4
                {
                    myMainIpAdress = ip;
                    break;
                }
            }

            if (myMainIpAdress != null)
            {
                NetworkInterface[] NetworkInterfaces =
                    NetworkInterface.GetAllNetworkInterfaces();

                foreach (NetworkInterface ni in NetworkInterfaces)
                {
                    if (ni.OperationalStatus == OperationalStatus.Up)
                    {
                        IPInterfaceProperties props = ni.GetIPProperties();
                        foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
                        {
                            if (ai.Address.Equals(myMainIpAdress))
                            {
                                return ni;
                            }
                        }
                    }
                }
            }

            return null;
        }

        // ******************************************************************
        /// <summary>
        /// AddressFamily.InterNetwork = IPv4
        /// Thanks to Dr. Wilys Apprentice at
        /// http://stackoverflow.com/questions/1069103/how-to-get-the-ip-address-of-the-server-on-which-my-c-sharp-application-is-runni
        /// using System.Net.NetworkInformation;
        /// </summary>
        /// <param name="mac"></param>
        /// <param name="addressFamily">AddressFamily.InterNetwork = IPv4,  AddressFamily.InterNetworkV6 = IPv6</param>
        /// <returns></returns>
        public static IPAddress GetIpFromMac(PhysicalAddress mac, AddressFamily addressFamily = AddressFamily.InterNetwork)
        {
            NetworkInterface[] NetworkInterfaces =
                NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface ni in NetworkInterfaces)
            {
                if (ni.GetPhysicalAddress().Equals(mac))
                {
                    if (ni.OperationalStatus == OperationalStatus.Up)
                    {
                        IPInterfaceProperties props = ni.GetIPProperties();
                        foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
                        {
                            if (ai.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)
                            {
                                if (ai.Address.AddressFamily == addressFamily)
                                {
                                    return ai.Address;
                                }
                            }
                        }
                    }
                }
            }

            return null;
        }

        // ******************************************************************
        /// <summary>
        /// Return the best guess of main ipAdress. To get it in the form aaa.bbb.ccc.ddd just call 
        /// '?.ToString() ?? ""' on the result.
        /// </summary>
        /// <returns></returns>
        public static IPAddress GetMyInternetIpAddress()
        {
            NetworkInterface ni = GetMainNetworkInterface();
            IPAddress ipAddress = GetIpFromMac(ni.GetPhysicalAddress());
            if (ipAddress == null) // could it be possible ?
            {
                ipAddress = GetIpFromMac(ni.GetPhysicalAddress(), AddressFamily.InterNetworkV6);
            }

            return ipAddress;
        }

        // ******************************************************************
        public static bool IsBroadcastAddress(IPAddress ipAddress)
        {
            if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
            {
                return ipAddress.GetAddressBytes()[3] == 255;
            }

            if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
            {
                return false; // NO broadcast in IPv6
            }

            return false;
        }

        // ******************************************************************
        public static bool IsMulticastAddress(IPAddress ipAddress)
        {
            if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
            {
                // Source: https://technet.Microsoft.com/en-us/library/cc772041(v=ws.10).aspx
                return ipAddress.GetAddressBytes()[0] >= 224 && ipAddress.GetAddressBytes()[0] <= 239;
            }

            if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
            {
                return ipAddress.IsIPv6Multicast;
            }

            return false;
        }

        // ******************************************************************

    }
}
1
Eric Ouellet
using System;
using System.Net;

namespace IPADDRESS
{
    class Program
    {
        static void Main(string[] args)
        {
            String strHostName = string.Empty;
            if (args.Length == 0)
            {                
                /* First get the Host name of local machine.*/
                strHostName = Dns.GetHostName();
                Console.WriteLine("Local Machine's Host Name: " + strHostName);
            }
            else
            {
                strHostName = args[0];
            }
            /* Then using Host name, get the IP address list..*/
            IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            for (int i = 0; i < addr.Length; i++)
            {
                Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
            }
            Console.ReadLine();
        }
    }
}
1
sundram
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);

Une simple ligne de code qui renvoie la première adresse IPV4 interne ou la valeur null s'il n'y en a pas. Ajouté en tant que commentaire ci-dessus, mais peut être utile à quelqu'un (certaines solutions ci-dessus renverront plusieurs adresses nécessitant un filtrage supplémentaire).

Il est également facile de retourner en boucle au lieu de null, je suppose avec:

return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork) ?? new IPAddress( new byte[] {127, 0, 0, 1} );
1
Wolf5370

Pour trouver la liste d'adresses IP, j'ai utilisé cette solution

public static IEnumerable<string> GetAddresses()
{
    var Host = Dns.GetHostEntry(Dns.GetHostName());
    return (from ip in Host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}

Mais j'aime personnellement la solution ci-dessous pour obtenir l'adresse IP locale valide 

public static IPAddress GetIPAddress(string hostName)
{
    Ping ping = new Ping();
    var replay = ping.Send(hostName);

    if (replay.Status == IPStatus.Success)
    {
        return replay.Address;
    }
    return null;
 }

public static void Main()
{
    Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
    Console.WriteLine("Google IP:" + GetIPAddress("google.com");
    Console.ReadLine();
}
1
Ravi Shankar

La solution LINQ:

Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""
1
Serge
namespace NKUtilities 
{
    using System;
    using System.Net;

    public class DNSUtility
    {
        public static int Main (string [] args)
        {

          String strHostName = new String ("");
          if (args.Length == 0)
          {
              // Getting Ip address of local machine...
              // First get the Host name of local machine.
              strHostName = Dns.GetHostName ();
              Console.WriteLine ("Local Machine's Host Name: " +  strHostName);
          }
          else
          {
              strHostName = args[0];
          }

          // Then using Host name, get the IP address list..
          IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
          IPAddress [] addr = ipEntry.AddressList;

          for (int i = 0; i < addr.Length; i++)
          {
              Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
          }
          return 0;
        }    
     }
}
1
naani

La question ne dit pas ASP.NET MVC mais je la laisse simplement ici:

Request.UserHostAddress
1
Barry Guvenkaya

Peut-être que par external IP, vous pouvez envisager (si vous êtes dans un contexte de serveur Web) en utilisant cette

Request.ServerVariables["LOCAL_ADDR"];

Je posais la même question que vous et je l’ai trouvée dans l’article this stackoverflow.

Cela a fonctionné pour moi.

1
Juan Calero

Voici comment je l'ai résolu. Je sais que si vous avez plusieurs interfaces physiques, cela ne sélectionnera peut-être pas exactement l'éthique que vous souhaitez.

private string FetchIP()
{
    //Get all IP registered
    List<string> IPList = new List<string>();
    IPHostEntry Host;
    Host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (IPAddress ip in Host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            IPList.Add(ip.ToString());
        }
    }

    //Find the first IP which is not only local
    foreach (string a in IPList)
    {
        Ping p = new Ping();
        string[] b = a.Split('.');
        string ip2 = b[0] + "." + b[1] + "." + b[2] + ".1";
        PingReply t = p.Send(ip2);
        p.Dispose();
        if (t.Status == IPStatus.Success && ip2 != a)
        {
            return a;
        }
    }
    return null;
}
1
Thomas Andreè Lian

Obtenez toutes les adresses IP sous forme de chaînes à l'aide de LINQ:

using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
...
string[] allIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
    .SelectMany(c=>c.GetIPProperties().UnicastAddresses
        .Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork)
        .Select(d=>d.Address.ToString())
    ).ToArray();

FILTRER LES PARTICULIERS ...

Tout d’abord, définissez une méthode d’extension IsPrivate():

public static class IPAddressExtensions
{
    // Collection of private CIDRs (IpAddress/Mask) 
    private static Tuple<int, int>[] _privateCidrs = new []{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}
        .Select(c=>Tuple.Create(BitConverter.ToInt32(IPAddress
                                    .Parse(c.Split('/')[0]).GetAddressBytes(), 0)
                              , IPAddress.HostToNetworkOrder(-1 << (32-int.Parse(c.Split('/')[1])))))
        .ToArray();
    public static bool IsPrivate(this IPAddress ipAddress)
    {
        int ip = BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0);
        return _privateCidrs.Any(cidr=>(ip & cidr.Item2)==(cidr.Item1 & cidr.Item2));           
    }
}

... Et ensuite, utilisez-le pour filtrer les IP privées:

string[] publicIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
    .SelectMany(c=>c.GetIPProperties().UnicastAddresses
        .Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork
            && !d.Address.IsPrivate() // Filter out private ones
        )
        .Select(d=>d.Address.ToString())
    ).ToArray();
1
Diego

Pour obtenir l'adresse IP à distance le plus rapidement possible. Vous devez utiliser un téléchargeur ou créer un serveur sur votre ordinateur.

L’inconvénient de l’utilisation de ce code simple (recommandé) est qu’il vous faudra 3 à 5 secondes pour obtenir votre adresse IP distante, car le WebClient, une fois initialisé, prend toujours 3 à 5 secondes pour vérifier vos paramètres de proxy.

 public static string GetIP()
 {
            string externalIP = "";
            externalIP = new WebClient().DownloadString("http://checkip.dyndns.org/");
            externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                           .Matches(externalIP)[0].ToString();
            return externalIP;
 }

Voici comment je l'ai corrigé. (La première fois prend encore 3 à 5 secondes), mais après cela, votre adresse IP distante sera toujours attribuée en 0 à 2 secondes, selon votre connexion.

public static WebClient webclient = new WebClient();
public static string GetIP()
{
    string externalIP = "";
    externalIP = webclient.DownloadString("http://checkip.dyndns.org/");
    externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                   .Matches(externalIP)[0].ToString();
    return externalIP;
}
0
SSpoke

Un autre moyen d'obtenir votre adresse IP publique consiste à utiliser le serveur resolve1.opendns.com d'OpenDNS avec myip.opendns.com comme demande.

Sur la ligne de commande c'est:

  nslookup myip.opendns.com resolver1.opendns.com

Ou en C # en utilisant le nuget DNSClient:

  var lookup = new LookupClient(new IPAddress(new byte[] { 208, 67, 222, 222 }));
  var result = lookup.Query("myip.opendns.com", QueryType.ANY);

C’est un peu plus propre que de toucher les points de terminaison http et d’analyser les réponses.

0
Ian Mercer

Et ceci consiste à obtenir toutes les adresses IP locales au format CSV en VB.NET

Imports System.Net
Imports System.Net.Sockets

Function GetIPAddress() As String
    Dim ipList As List(Of String) = New List(Of String)
    Dim Host As IPHostEntry
    Dim localIP As String = "?"
    Host = Dns.GetHostEntry(Dns.GetHostName())
    For Each ip As IPAddress In Host.AddressList
        If ip.AddressFamily = AddressFamily.InterNetwork Then
            localIP = ip.ToString()
            ipList.Add(localIP)
        End If
    Next
    Dim ret As String = String.Join(",", ipList.ToArray)
    Return ret
End Function
0
Saurabh Kumar