2012-11-21 20 views
9

Sto provando a fare questo C#. Devo trovare tutti gli indirizzi IP attivi nella mia rete e mostrarli in un elenco. Posso eseguire il ping di tutti gli indirizzi IP disponibili (1 ... 255) in una rete. Ma voglio rendere questo processo più veloce.trovare tutti gli indirizzi IP in una rete

+1

Se volete renderlo più veloce, ping tutti gli IP allo stesso tempo: 'Ping.SendAsync'. – igrimpe

+0

Ho appena eseguito un comando di ping come questo 'per/l% n in (1,1255) fare ping 192.168.10.% X' con process.start() e poi leggere la voce della tabella arp trovare ogni ip indirizzo nella rete. ma questo molto lento. Hai bisogno di farlo velocemente. –

+0

@MehbubeArman, quanti indirizzi IP sono possibili nella rete e cosa è "abbastanza veloce" –

risposta

1

Si prega di fare riferimento a This link su socket client asincrono per imparare come eseguire il ping più veloce.

Edit: Un rapido frammento su come raggiungere questo obiettivo:

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()); 
     } 
    } 

Tratto da this Microsoft documentation.

+0

grazie NewAmbition. Ma stavo cercando un'alternativa al pinging di tutti –

+1

perché stai cercando un'alternativa? (Anche allora, non l'hai mai detto nella tua domanda) - Il ping ti permetterà di vedere se un IP è attivo o meno. – TheGeekZn

+2

Se non esiste un punto di riferimento centrale come un server di dominio/server DNS con cui si registrano gli host, si dovrà raggiungere tutti gli indirizzi candidati e vedere se c'è qualcosa lì, il ping è il modo per farlo. –

-1

http://www.advanced-ip-scanner.com/. questo è uno strumento che puoi usare per vedere quali IP sono attivi sulla tua rete. anche quale tipo di hardware di rete utilizza il PC.

+0

In realtà stavo cercando una soluzione che implicasse la programmazione –

0
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 
      } 
     } 
    } 
10

Questo codice esegue la scansione della rete 255 segmenti di classe D in circa 1 secondo. L'ho scritto su VB.net e tradotto in C# (ci scusiamo se ci sono errori). Incollalo in un progetto Console ed esegui. Modifica secondo necessità.

Nota: Il codice è non produzione pronta e necessita miglioramenti sul particolare l'istanza di conteggio (provate implementare un TaskFactory con BlockingCollection invece).

Modificare ttl (time-to-live) e timeout se instabile risultato.

L'esecuzione del codice darà un risultato come questo:

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. 

codice 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(); 

    } 

} 

E il codice 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 
0

se si vuole andare alla Percorso ARP, puoi semplicemente inviare richieste ARP per tutti gli indirizzi, attendere un po 'e guardare nella tabella ARP del tuo host

questo può aiutare

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

+0

quindi stai limitando la soluzione agli host connessi alla sua sottorete ??? –

+1

sembra essere quello che vuole fare, e dovrebbe essere anche veloce. –

+0

la sua domanda non è chiara e questa soluzione offre poco più del ping –