zoukankan      html  css  js  c++  java
  • C#获得本地IP地址的各种方法

    网上有很多种方法可以获取到本地的IP地址。一线常用的有这么些:

    枚举本地网卡

    using System.Net.NetworkInformation;
    using System.Net.Sockets;
    
    foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces()
        .Where(a => a.SupportsMulticast)
        .Where(a => a.OperationalStatus == OperationalStatus.Up)
        .Where(a => a.NetworkInterfaceType != NetworkInterfaceType.Loopback)
        .Where(a => a.GetIPProperties().GetIPv4Properties() != null)
        .Where(a => a.GetIPProperties().UnicastAddresses.Any(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork))
        .Where(a => a.GetIPProperties().UnicastAddresses.Any(ua => ua.IsDnsEligible))
    )
    {
    
        Console.WriteLine("Network Interface: {0}", netif.Name);
        IPInterfaceProperties properties = netif.GetIPProperties();
        foreach (IPAddressInformation unicast in properties.UnicastAddresses)
            Console.WriteLine("	UniCast: {0}", unicast.Address);
    }
    

    获得的信息比较全面,相当于网卡的信息都能获取,但是不能区分虚拟网卡(比如docker)。

    尝试连接一个IP地址

    string localIP;
    using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
    {
        socket.Connect("8.8.8.8", 65530);
        IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
        localIP = endPoint.Address.ToString();
    }
    Console.WriteLine(localIP);
    

    可以避免虚拟网卡,但是对于内网地址,不一定适用,同时要求网络必须在线,并且有其他服务器可以进行连接。

    借用DNS解析

    using System.Net;
    
    string sHostName = Dns.GetHostName();
    IPHostEntry ipE = Dns.GetHostEntry(sHostName);
    IPAddress[] IpA = ipE.AddressList;
    for (int i = 0; i < IpA.Length; i++)
    {
        Console.WriteLine("IP Address {0}: {1} ", i, IpA[i].ToString());
    }
    

    IPAddress还可以继续通过筛选IPv4的方法进行更精确的选择,和第一种方法是类似的。操作方法非常简洁,但是和获得网卡信息一样,不能区分虚拟网卡。

    总结

    对于有双网卡的情况,往往两个网卡都是有效的IPV4地址,这个时候需要使用方法2通过局域网或者广域网内访问进行区分。当然也可以选择更为复杂的方式:在局域网内使用广播服务,然后再抓包确定获取的网络地址。

  • 相关阅读:
    CF703D Mishka and Interesting sum
    CF697D Puzzles
    SCOI2017酱油记
    [BZOJ4730][清华集训2016][UOJ266] Alice和Bob又在玩游戏
    BZOJ4311:向量
    BZOJ4520: [Cqoi2016]K远点对
    BZOJ4555: [Tjoi2016&Heoi2016]求和
    [Codechef November Challenge 2012] Arithmetic Progressions
    agc040
    补题
  • 原文地址:https://www.cnblogs.com/podolski/p/14133205.html
Copyright © 2011-2022 走看看