Question

I'm making a small userControl library that searches for active server on a specific port [LAN].
I'm using [.Net 4.0] TCP sockets (IPV4)
so first i get the IPAddresses of my computer from :

string sHostName = Dns.GetHostName();
IPHostEntry ipE = Dns.GetHostByName(sHostName);
IPAddress[] IpA = ipE.AddressList;

then i take first 3 parts of the IPAddress so if the input IPAddress = "192.168.1.X" it returns "192.168.1." using :

string scanIP = IpA[i].ToString().Substring(0, IpA[i].ToString().LastIndexOf(".")) + ".";

then i search from (ex: 192.168.1.1 - to 192.168.1.254)

what i need is to check if scanIP is duplicated to avoid scan 254 IPAddresses more than once.. because the array IpA may returns many IP Addresses (wireless network,wirenetwork,bluetooth network..etc) for ex : my wireless ip is : 192.168.1.25 and my ethernet ip is : 192.168.1.5

here's my code :

  public ServerDiscovery()
    {
        InitializeComponent();
        timer.Elapsed += timer_tick;
    }

    System.Timers.Timer timer = new System.Timers.Timer(5000);
    List<SocketAsyncEventArgs> list = new List<SocketAsyncEventArgs>();

    private void btnRefresh_Click(object sender, EventArgs e)
    {
        listServer.Items.Clear();
        timer.Start();
        //getting array of IP Addresses.
        IPAddress[] IpA = Dns.GetHostByName(Dns.GetHostName()).AddressList;

        for(int j = 0; j < IpA.Length; j++)
        {
            if (IpA[j].AddressFamily == AddressFamily.InterNetwork)  //checking if IP is version 4
            {
                string scanIP = IpA[j].ToString().Substring(0, IpA[j].ToString().LastIndexOf(".")) + ".";
                if (some condition)// i need a condition to ensure that dublicated scanIP doesn't scan again
                {
                    Parallel.For(1, 255, (i, loopState) =>
                        {
                            Scan(scanIP + i);
                        });
                }
            }
        }
    }

    private void Scan(string ipAdd)
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        SocketAsyncEventArgs e = new SocketAsyncEventArgs();
        e.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(ipAdd), 9990);
        e.UserToken = s;
        e.Completed += new EventHandler<SocketAsyncEventArgs>(e_Completed);
        list.Add(e);
        s.ConnectAsync(e);
    }

    private void e_Completed(object sender, SocketAsyncEventArgs e)
    {
        if (e.ConnectSocket != null)
        {
            StreamReader sr = new StreamReader(new NetworkStream(e.ConnectSocket));
            ListViewItem item = new ListViewItem();
            string[] cmd = sr.ReadLine().Split('<');
            item.Text = cmd[0];
            item.SubItems.Add(((IPEndPoint)e.RemoteEndPoint).Address.ToString());
            item.SubItems.Add(cmd[1]);
            AddServer(item);
        }
    }

    delegate void AddItem(ListViewItem item);
    private void AddServer(ListViewItem item)
    {
        if (InvokeRequired)
        {
            Invoke(new AddItem(AddServer), item);
            return;
        }
        listServer.Items.Add(item);
    }

    private void timer_tick(object sender, EventArgs e)
    {
        timer.Stop();
        foreach (var s in list)
        {
            ((Socket)s.UserToken).Dispose();
        }
    }
Était-ce utile?

La solution

You could employ HashSet to keep already used addresses.

HashSet<string> usedIP = new HashSet<string>();

Replace SomeCondition with

if (!usedIp.Contains(scanIP))
{
   usedIP.Add(scanIP);
   Parallel.For(1, 255, (i, loopState) =>
                {
                     Scan(scanIP + i);
                });
}

Autres conseils

The simplest approach is to use Distinct() LINQ extension method:

    IpA = IpA.Distinct().ToArray();
    for(int j = 0; j < IpA.Length; j++)
    {
    ...

You can also use a HashSet to check the duplicates. I think it is a faster solution:

    HashSet<IPAddress> set = new HashSet<IPAddress>(IpA);
    for(int j = 0; j < IpA.Length; j++)
    {
        if( set.Contains(IpA[j]) )
            continue;
        set.Add(IpA[j]);

        if (IpA[j].AddressFamily == AddressFamily.InterNetwork)  //checking if IP is version 4
        {
            string scanIP = IpA[j].ToString().Substring(0, IpA[j].ToString().LastIndexOf(".")) + ".";
            Parallel.For(1, 255, (i, loopState) =>
                {
                    Scan(scanIP + i);
                });
        }
    }

add scanIP to a dictionary, and make sure it hasn't already been added.

Dictionary<string, string> scannedIPs = new Dictionary<string, string>();

...

string scanIP = IpA[j].ToString().Substring(0, IpA[j].ToString().LastIndexOf(".")) + ".";
if (!scannedIPs.ContainsKey(scanIP))
{
   scannedIPs.Add(scanIP, scanIP);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top