5

I want to get the IP Addresses of all the machines connected to my PC using C#, but I don't want to use the Ping method because it takes a lot of time especially when the range of IP addresses is very wide.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 3
    Ping does not tell you what is connected to your machine. – Svek May 31 '17 at 06:09
  • Ping only implies that the target IP in the *network* is alive. And frankly it is not very good at that; sometimes packets get lost in the way. I used to do an IP sweeping 5 times consecutively using an async `Task` for each address (It takes around 0.4 seconds). – mcy May 31 '17 at 07:56

1 Answers1

7

Getting all the active TCP connections

Use the IPGlobalProperties.GetActiveTcpConnections Method

using System.Net.NetworkInformation;

public static void ShowActiveTcpConnections()
{
    Console.WriteLine("Active TCP Connections");
    IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
    TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
    foreach (TcpConnectionInformation c in connections)
    {
        Console.WriteLine("{0} <==> {1}",
                          c.LocalEndPoint.ToString(),
                          c.RemoteEndPoint.ToString());
    }
}

source:
https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipglobalproperties.getactivetcpconnections.aspx

Note: This only gives you the active TCP connections.


Shorter version of the code above.

foreach (var c in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections())
{
    ...
}

Getting all the machines connected to a network

It might be better to do a ping sweep. Takes a few seconds to do 254 ip addresses. Solution is here https://stackoverflow.com/a/4042887/3645638

Svek
  • 12,350
  • 6
  • 38
  • 69
  • I tested it, it gives me the active pc, there are other connected instruments connected to my pc (PLC) it connects via ethernet, but I couldn't see it in the lists, how can i see it in addition to the PCs – Memduh Cüneyt Sep 21 '17 at 08:00