Comment obtenir l'adresse IP du serveur sur lequel tourne mon application C#?

j'exécute un serveur, et je veux afficher ma propre adresse IP.

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

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. Est-il un meilleur moyen pour le faire?

357
demandé sur Nate Diamond 2009-07-01 17:20:23

25 réponses

Non, c'est à peu près la meilleure façon de le faire. Comme une machine pourrait avoir plusieurs adresses IP, vous devez itérer la collection d'entre eux pour trouver la bonne.

Edit: La seule chose que je serait changement serait de changer ceci:

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

à ceci:

if (ip.AddressFamily == AddressFamily.InterNetwork)

il n'est pas nécessaire de ToString une énumération pour comparaison.

233
répondu Andrew Hare 2009-07-01 14:50:17

la seule façon de connaître votre PI 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;
}
162
répondu ezgar 2012-05-21 14:48:39

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
répondu Mohammed A. Fadil 2013-08-21 10:15:59

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

Le Système.Net.NetworkInformation namespace contient une classe NetworkInterface class , qui a une méthode statique GetAllNetworkInterfaces method .

cette méthode renverra toutes les" interfaces réseau " sur votre machine, et il y en a généralement quelques-unes, même si vous ayez un adaptateur sans fil et/ou un matériel d'adaptateur ethernet installé sur votre machine. Toutes ces interfaces réseau ont des adresses IP valides pour votre machine locale, bien que vous n'en vouliez probablement qu'une.

si vous cherchez une adresse IP, vous devez filtrer la liste jusqu'à ce que vous puissiez identifier la bonne adresse. Vous aurez probablement besoin de faire quelques expériences, mais j'ai eu du succès avec l'approche suivante:

  • Filtrer toutes les interfaces réseau qui sont inactives en vérifiant OperationalStatus == OperationalStatus.Up . Cela exclura votre adaptateur ethernet physique, par exemple, si vous n'avez pas de câble réseau Branché.

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

  • filtrer les adresses unicast non préférées en cochant la case DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
  • filtrer les adresses" virtuelles "en cochant la case AddressPreferredLifetime != UInt32.MaxValue .

à ce point je prends l'adresse de la première (s'il y a lieu) adresse unicast qui correspond à tous ces filtres.

EDIT:

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

l'échantillon ci-dessous montre un filtrage basé sur l'état opérationnel, la famille d'adresses, à l'exclusion de l'adresse loopback (127.0.0.1), l'état de détection d'adresse dupliquée et 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
répondu Dr. Wily's Apprentice 2018-05-16 16:09:00
WebClient webClient = new WebClient();
string IP = webClient.DownloadString("http://myip.ozymo.com/");
37
répondu James 2010-12-20 18:20:13
using System.Net;

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

vient de tester ceci sur ma machine et cela fonctionne.

17
répondu opedog 2009-07-01 13:26:15

si vous voulez éviter d'utiliser le DNS

List<IPAddress> ipList = new List<IPAddress>();
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces()) {
    foreach (var ua in ni.GetIPProperties().UnicastAddresses) {
        if (ua.Address.AddressFamily == AddressFamily.InterNetwork) {
            Console.WriteLine("found ip " + ua.Address.ToString());
            ipList.Add(ua.Address);
        }
    }
}
14
répondu reza 2016-01-26 01:31:01

ne vous fiez pas tout le temps à InterNetwork parce que vous pouvez avoir plus d'un appareil qui utilise aussi IP4 ce qui gâcherait les résultats en obtenant votre IP. Maintenant, si vous voulez vous pouvez simplement copier cela et s'il vous plaît consulter ou mettre à jour la façon dont vous voyez l'ajustement.

tout d'abord je reçois l'adresse du routeur (passerelle) S'il revient que je suis connecté à une passerelle (ce qui signifie pas connecté directement dans le modem sans fil ou pas) alors nous avons notre adresse de passerelle comme IPAddress sinon nous avons un pointeur nul de référence IPAddress.

alors nous devons obtenir la liste de l'ordinateur des adresses IP. C'est là que les choses ne sont pas si dures parce que les routeurs (tous les routeurs) utilisent 4 octets (...). Les trois premiers sont les plus importants car tout ordinateur connecté aura l'adresse IP4 correspondant aux trois premiers octets. Ex: 192.168.0.1 est la norme pour L'IP par défaut du routeur à moins qu'elle ne soit modifiée par l'administrateur. "192.168.0" ou ce qu'ils peuvent être est ce que nous besoin de faire correspondre. Et c'est tout ce que j'ai fait dans la fonction Adressedofgateway. La raison de la correspondance de longueur est parce que toutes les adresses (qui sont pour l'ordinateur seulement) ont la longueur de 4 octets. Si vous tapez netstat dans le cmd, vous trouverez que cela est vrai. Donc là vous l'avez. Oui, il faut un peu plus de travail pour vraiment obtenir ce que vous cherchez. Processus d'élimination. Et pour L'amour de Dieu, ne trouvez pas l'adresse en la gravant ce qui prend du temps parce que d'abord vous envoyez le adresse à être annelé et ensuite il doit renvoyer le résultat. Non, travaillez directement avec les classes .Net qui traitent de l'environnement de votre 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 le même parce que le modem est votre passerelle mais le sous-masque n'est pas le même parce que vous obtenez l'information directement à partir de votre serveur DNS via modem et non masqué par le routeur qui vous sert Internet même si vous pouvez toujours utiliser le même code parce que le dernier octet de L'IP assignée au modem est 1. Donc si L'adresse IP envoyée par le modem qui change est 111.111.111' , alors vous obtiendrez 111.111.111.(quelques octets de la valeur). Gardez à l'esprit que nous devons trouver l'information de passerelle parce qu'il ya plus d'appareils qui traitent de la connectivité internet que votre routeur et le modem.

Maintenant vous voyez pourquoi vous ne changez pas les deux premiers routeurs octets 192 et 168. Ceux-ci sont strictement distingués pour les routeurs seulement et pas l'utilisation d'internet ou nous aurions un problème sérieux avec le protocole IP et la double pinging résultant en une panne de votre ordinateur. L'image que votre IP de routeur assignée est 192.168.44.103 et vous cliquez sur un site avec cette IP aussi. OMG! Votre ordinateur ne saurait pas quoi faire. Crash de là. Pour éviter ce problème, seuls les routeurs sont assignés et pas pour l'utilisation internet. Laissez donc 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
répondu bvrwoo_3376 2012-05-27 15:22:29

j'ai juste pensé que je voudrais ajouter mon propre, un-liner (même s'il ya beaucoup d'autres réponses utiles déjà).


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

8
répondu bæltazor 2013-06-27 16:05:51

pour obtenir l'adresse IP publique actuelle, tout ce que vous devez faire est de créer une page ASPX avec la ligne suivante sur l'événement page load:

Response.Write(HttpContext.Current.Request.UserHostAddress.ToString());
4
répondu detect the public IP address 2011-11-24 16:36:06

si vous utilisez l'intranet, vous pourrez obtenir l'adresse IP de la machine locale et si ce n'est pas le cas, vous obtiendrez l'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
répondu Guilherme Ferreira 2014-03-17 13:32:50
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;
            }
        }
    }
}

Look ici pour plus de détails.

vous devez vous rappeler que votre ordinateur peut avoir plus d'une adresse IP (en fait il a toujours) - donc lequel êtes-vous après.

3
répondu mfloryan 2011-11-28 20:45:39

essayez ceci:

 IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
 String MyIp = localIPs[0].ToString();
2
répondu The Mask 2012-06-19 21:53:30

peut-être par externe IP vous pouvez considérer (si vous êtes dans un contexte de serveur Web) en utilisant ce

Request.ServerVariables["LOCAL_ADDR"];

je posais la même question que vous et je l'ai trouvé dans cet article stackoverflow.

ça a marché pour moi.

1
répondu Juan Calero 2017-05-23 11:33:16
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
répondu naani 2012-05-23 03:53:12
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
répondu sundram 2012-06-04 17:40:36
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);

Simple ligne de code qui renvoie la première adresse IPV4 interne ou nul s'il n'y en a pas. Ajouté comme commentaire ci-dessus, mais peut être utile à quelqu'un (certaines solutions ci-dessus retourneront plusieurs adresses qui ont besoin d'un filtrage plus poussé).

il est aussi facile de retourner loopback 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
répondu Wolf5370 2012-08-23 12:31:15

pour trouver la liste des 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 local valide adresse IP

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
répondu Ravi Shankar 2013-03-14 06:59:08

The LINQ solution:

Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""
1
répondu Serge 2013-04-16 09:15:49

, Voici comment je l'ai résolu. je sais que si vous avez plusieurs interfaces physiques, cela pourrait ne pas sélectionner exactement l'eth que vous voulez.

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
répondu Thomas Andreè Lian 2014-01-18 21:47:33

la question ne dit pas ASP.NET MVC mais je laisse juste ceci ici de toute façon:

Request.UserHostAddress
1
répondu Barry Guvenkaya 2015-05-21 02:25:39

obtenir toutes les adresses IP comme Chaînes en utilisant 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();

POUR FILTRER LES PRIVÉS...

tout d'abord, définir 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 puis l'utiliser pour filtrer les IPs privés:

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
répondu Diego 2015-10-15 20:58:58

ça me va... et devrait être plus rapide dans la plupart des cas (si pas 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
/// /q/how-to-get-the-ip-address-of-the-server-on-which-my-c-application-is-running-on-6126/"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;
}

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

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
        /// /q/how-to-get-the-ip-address-of-the-server-on-which-my-c-application-is-running-on-6126/"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
répondu Eric Ouellet 2017-08-24 17:52:49

et ceci pour obtenir tous les IPs locaux en format csv 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
répondu Saurabh Kumar 2012-04-26 01:13:40

pour obtenir l'adresse IP distante le plus rapidement possible. Vous devez utiliser un downloader, ou créer un serveur sur votre ordinateur.

les inconvénients de l'utilisation de ce code simple: (qui est recommandé) est qu'il faudra 3-5 secondes pour obtenir votre adresse IP à distance parce que le WebClient une fois initialisé prend toujours 3-5 secondes pour vérifier les paramètres de votre 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 réparé.. (la première fois prend encore 3-5 secondes) mais après cela, il obtiendra toujours votre adresse IP distante 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
répondu SSpoke 2015-09-29 21:13:33