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.