简体   繁体   English

找到网络中的所有IP地址

[英]find all ip address in a network

I am trying to do this C#. 我正在尝试做这个C#。 I need to find all ip address that are active in my network and show them in a list. 我需要找到在我的网络中活动的所有IP地址并在列表中显示它们。 I can ping all available (1...255) ip address in a network. 我可以ping网络中所有可用的(1 ... 255)IP地址。 But I want to make this process faster. 但我想让这个过程更快。

This code scans my network 255 D-class segments in about 1 sec. 此代码在大约1秒内扫描我的网络255个D级段。 I wrote it in VB.net and translated it to C# (apologies if there are any errors). 我在VB.net中写了它并将其翻译成C#(如果有任何错误就道歉)。 Paste it into a Console project and run. 将其粘贴到Console项目中并运行。 Modify as needed. 根据需要修改。

Note: The code is not production ready and need improvements on especially the instance counting (try implement a TaskFactory with a BlockingCollection instead). 注意:代码不是生产就绪的,需要对特别是实例计数进行改进(尝试使用BlockingCollection实现TaskFactory )。

Modify ttl (time-to-live) and timeout if unstable result-wise. 修改ttl(生存时间)并在结果不稳定时超时。

Running the code will give a result like this: 运行代码将得到如下结果:

Pinging 255 destinations of D-class in 192.168.1.*
Active IP: 192.168.1.100
Active IP: 192.168.1.1
Finished in 00:00:00.7226731. Found 2 active IP-addresses.

C# code: C#代码:

using System.Net.NetworkInformation;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System;

static class Module1
{
    private static List<Ping> pingers = new List<Ping>();
    private static int instances = 0;

    private static object @lock = new object();

    private static int result = 0;
    private static int timeOut = 250;

    private static int ttl = 5;

    public static void Main()
    {
        string baseIP = "192.168.1.";

        Console.WriteLine("Pinging 255 destinations of D-class in {0}*", baseIP);

        CreatePingers(255);

        PingOptions po = new PingOptions(ttl, true);
        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
        byte[] data = enc.GetBytes("abababababababababababababababab");

        SpinWait wait = new SpinWait();
        int cnt = 1;

        Stopwatch watch = Stopwatch.StartNew();

        foreach (Ping p in pingers) {
            lock (@lock) {
                instances += 1;
            }

            p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeOut, data, po);
            cnt += 1;
        }

        while (instances > 0) {
            wait.SpinOnce();
        }

        watch.Stop();

        DestroyPingers();

        Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result);
        Console.ReadKey();

    }

    public static void Ping_completed(object s, PingCompletedEventArgs e)
    {
        lock (@lock) {
            instances -= 1;
        }

        if (e.Reply.Status == IPStatus.Success) {
            Console.WriteLine(string.Concat("Active IP: ", e.Reply.Address.ToString()));
            result += 1;
        } else {
            //Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString()))
        }
    }


    private static void CreatePingers(int cnt)
    {
        for (int i = 1; i <= cnt; i++) {
            Ping p = new Ping();
            p.PingCompleted += Ping_completed;
            pingers.Add(p);
        }
    }

    private static void DestroyPingers()
    {
        foreach (Ping p in pingers) {
            p.PingCompleted -= Ping_completed;
            p.Dispose();
        }

        pingers.Clear();

    }

}

And VB.net code: 和VB.net代码:

Imports System.Net.NetworkInformation
Imports System.Threading

Module Module1

    Private pingers As New List(Of Ping)

    Private instances As Integer = 0
    Private lock As New Object

    Private result As Integer = 0

    Private timeOut As Integer = 250
    Private ttl As Integer = 5

    Sub Main()

        Dim baseIP As String = "192.168.1."
        Dim classD As Integer = 1

        Console.WriteLine("Pinging 255 destinations of D-class in {0}*", baseIP)

        CreatePingers(255)

        Dim po As New PingOptions(ttl, True)
        Dim enc As New System.Text.ASCIIEncoding
        Dim data As Byte() = enc.GetBytes("abababababababababababababababab")

        Dim wait As New SpinWait
        Dim cnt As Integer = 1

        Dim watch As Stopwatch = Stopwatch.StartNew

        For Each p As Ping In pingers
            SyncLock lock
                instances += 1
            End SyncLock

            p.SendAsync(String.Concat(baseIP, cnt.ToString()), timeOut, data, po)
            cnt += 1
        Next

        Do While instances > 0
            wait.SpinOnce()
        Loop

        watch.Stop()

        DestroyPingers()

        Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result)
        Console.ReadKey()

    End Sub

    Sub Ping_completed(s As Object, e As PingCompletedEventArgs)

        SyncLock lock
            instances -= 1
        End SyncLock

        If e.Reply.Status = IPStatus.Success Then
            Console.WriteLine(String.Concat("Active IP: ", e.Reply.Address.ToString()))
            result += 1
        Else
            'Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString()))
        End If

    End Sub

    Private Sub CreatePingers(cnt As Integer)

        For i As Integer = 1 To cnt
            Dim p As New Ping
            AddHandler p.PingCompleted, AddressOf Ping_completed
            pingers.Add(p)
        Next
    End Sub
    Private Sub DestroyPingers()

        For Each p As Ping In pingers
            RemoveHandler p.PingCompleted, AddressOf Ping_completed
            p.Dispose()
        Next

        pingers.Clear()

    End Sub

End Module

Please refer to This link about Asynchronous Client Socket to learn how to ping faster. 请参阅此链接有关异步客户端套接字以了解如何更快地ping。

Edit: A quick snippet on how to accomplish this: 编辑:关于如何完成此操作的快速摘录:

private static void StartClient() {
        // Connect to a remote device.
        try {
            // Establish the remote endpoint for the socket.
            // The name of the 
            // remote device is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect( remoteEP, 
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            // Send test data to the remote device.
            Send(client,"This is a test<EOF>");
            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();

        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }

Taken from this Microsoft documentation. 摘自此Microsoft文档。

    public static void NetPing()
    {            
        Ping pingSender = new Ping();
        foreach (string adr in stringAddressList)
        {
           IPAddress address = IPAddress.Parse(adr);
           PingReply reply = pingSender.Send (address);

           if (reply.Status == IPStatus.Success)
           {
                //Computer is active
           }
           else
           {
                //Computer is down
           }
        }  
    }

if you want to go the ARP route, you can simply send out ARP requests for all adresses, wait a bit, and look into the ARP table of your host 如果你想进入ARP路由,你可以简单地发送所有地址的ARP请求,稍等一下,然后查看主机的ARP表

this may help 这可能有所帮助

http://www.codeguru.com/cpp/in/internet/internetprotocolip/article.php/c6153/How-to-Get-an-ARP-Table-with-an-IP-Helper-API.htm http://www.codeguru.com/cpp/in/internet/internetprotocolip/article.php/c6153/How-to-Get-an-ARP-Table-with-an-IP-Helper-API.htm

http://www.advanced-ip-scanner.com/ . http://www.advanced-ip-scanner.com/ this a tool you can use to see what ip's are active on your network. 这是一个工具,您可以使用它来查看网络上的哪些IP处于活动状态。 also what type of network hardware that PC uses. 还有什么类型的PC使用的网络硬件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM