Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7654407
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T12:14:56+00:00 2026-05-31T12:14:56+00:00

I’ve been reading about how to check for all listening server on a specific

  • 0

I’ve been reading about how to check for all listening server on a specific port on LAN and finally I’ve wrote some code that it works as I want.
I’m using System.Threading.Tasks.Parallel to connect to all 254 IP Addresses as fast as possible
ex : 192.168.1.1 – 192.168.1.254

What I need is to set a timeout for these connection attempts, because it takes about 15-20 seconds to print : "Connection Failed " when it fails .. so How do I do that?

Here’s Client Code:

static void Main(string[] args)
    {
        Console.WriteLine("Connecting to IP addresses has started. \n");

        Parallel.For(1, 255, i =>
        {
            Connect("192.168.1." + i);
        });
        Console.ReadLine();
    }

    private static void Connect(string ipAdd)
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        SocketAsyncEventArgs e = new SocketAsyncEventArgs();
        IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse(ipAdd), 9990);
        e.RemoteEndPoint = ipEnd;
        e.UserToken = s;
        e.Completed += new EventHandler<SocketAsyncEventArgs>(e_Completed);
        Console.WriteLine("Trying to connect to : " + ipEnd);
        s.ConnectAsync(e);
    }
    private static void e_Completed(object sender, SocketAsyncEventArgs e)
    {
        if (e.ConnectSocket != null)
        {
            StreamReader sr = new StreamReader(new NetworkStream(e.ConnectSocket));
            Console.WriteLine("Connection Established : " + e.RemoteEndPoint + " PC NAME : " + sr.ReadLine());
        }
        else
        {
            Console.WriteLine("Connection Failed : " + e.RemoteEndPoint);
        }
    }

Server Code:

static void Main(string[] args)
    {
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ep = new IPEndPoint(IPAddress.Any,9990);
        server.Bind(ep);
        server.Listen(100);
        Socket client = server.Accept();
        NetworkStream stream = new NetworkStream(client);
        StreamWriter sw = new StreamWriter(stream)
        sw.WriteLine(System.Environment.MachineName);
        sw.Flush();
        sw.Dispose();
        stream.Dispose();
        client.Dispose();
        server.Dispose();
    }

If there’s any hint or notice that makes it better please tell me. I’m using [.Net 4.0] Sockets TCP.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T12:14:57+00:00Added an answer on May 31, 2026 at 12:14 pm

    I’ve figured out a solution.
    first add all created sockets to a list of type SocketAsyncEventArgs or type ofSocket or
    then use System.Timers.Timer to close all pending connection and the connected one after when the timer ticks which is after 5 seconds. (timer.Interval = 5000).

    Client Code:

       //I've changed my console application to Winform
       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)
        {
            timer.Start();
            Parallel.For(1, 255, (i, loopState) =>
            {
                ConnectTo("192.168.1." + i);
            });
        }
    
        private void ConnectTo(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);      // Add to a list so we dispose all the sockets when the timer ticks.
            s.ConnectAsync(e);
        }
    
        private void e_Completed(object sender, SocketAsyncEventArgs e)
        {
            if (e.ConnectSocket != null)     //if there's a connection Add its info to a listview
            {
                StreamReader sr = new StreamReader(new NetworkStream(e.ConnectSocket));
                ListViewItem item = new ListViewItem();
                item.Text = sr.ReadLine();
                item.SubItems.Add(((IPEndPoint)e.RemoteEndPoint).Address.ToString());
                item.SubItems.Add("Online");
                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();     //disposing all sockets that's pending or connected.
            }
        }
    

    enter image description here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have a text area in my form which accepts all possible characters from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.