如何获取连接到网络的计算机列表?

时间:2013-01-06 19:27:04

标签: c# .net networking

  

可能重复:
  Get a list of all computers on a network w/o DNS

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

1 个答案:

答案 0 :(得分:6)

我不知道从哪里获得此代码。 最后一段代码来自我(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;
    }