2

可能重复:
获取没有 DNS 的网络上所有计算机的列表

我正在创建一个应用程序,您可以在其中在网络上的计算机之间发送信息。计算机侦听连接并可以将信息发送到网络上的另一台计算机。我需要知道如何获取计算机所连接网络上的主机名或 IP 地址列表。

4

1 回答 1

8

我不知道我从哪里得到这个代码了。最后一段代码来自我(getIPAddress())

它读取您的 ip 以获取网络的基本 ip。

致谢作者:

static void Main(string[] args)
    {
        string ipBase = getIPAddress();
        string [] ipParts = ipBase.Split('.');
        ipBase = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + ".";
        for (int i = 1; i < 255; i++)
        {
            string ip = ipBase + i.ToString();

            Ping p = new Ping();
            p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
            p.SendAsync(ip, 100, ip);
        }
        Console.ReadLine();
    }

    static void p_PingCompleted(object sender, PingCompletedEventArgs e)
    {
        string ip = (string)e.UserState;
        if (e.Reply != null && e.Reply.Status == IPStatus.Success)
        {
            if (resolveNames)
            {
                string name;
                try
                {
                    IPHostEntry hostEntry = Dns.GetHostEntry(ip);
                    name = hostEntry.HostName;
                }
                catch (SocketException ex)
                {
                    name = "?";
                }
                Console.WriteLine("{0} ({1}) is up: ({2} ms)", ip, name, e.Reply.RoundtripTime);
            }
            else
            {
                Console.WriteLine("{0} is up: ({1} ms)", ip, e.Reply.RoundtripTime);
            }
            lock (lockObj)
            {
                upCount++;
            }
        }
        else if (e.Reply == null)
        {
            Console.WriteLine("Pinging {0} failed. (Null Reply object?)", ip);
        }
    }

    public static string getIPAddress()
    {
        IPHostEntry host;
        string localIP = "";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
            }
        }
        return localIP;
    }
于 2013-01-06T19:35:56.073 回答