Checking if a port is listening

Lucien via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Mar 26 02:37:55 PDT 2016


On Wednesday, 16 March 2016 at 20:44:12 UTC, Lucien wrote:
> Hello,
>
> I want to know if a port of an ip address is listening, 
> actually, I've this :
> http://pastebin.com/pZhm0ujy
> (checking port 22/ssh)
>
> It works, but it took me ~10min to scan 30 addresses.
>
> How can reduce the expiration delay ?

Finally solved :

---------------------------------------------

import std.stdio;
import std.socket;
import std.conv;
import core.time;
import core.thread;

void main()
{
     enum TRIES = 5, MAX = 254;

     string subnet = "192.168.0.";
     Socket[] sockets = new Socket[MAX];
     SocketSet ss = new SocketSet(MAX + 1);

     for (int i = 0; i < MAX; i++)
     {
         string ip = subnet~to!string(i+1);

         InternetAddress ia = new InternetAddress(ip, 22);

         TcpSocket s = new TcpSocket();
         s.blocking = false;
         s.setOption(SocketOptionLevel.SOCKET, 
SocketOption.RCVTIMEO, 100.msecs);
         s.setOption(SocketOptionLevel.SOCKET, 
SocketOption.SNDTIMEO, 100.msecs);
         s.connect(ia);

         sockets[i] = s;
     }

     for (int i = 0; i < TRIES; i++) {
         ss.reset();
         foreach (s; sockets) {
             if (s !is null)
                 ss.add(s);
         }
         int status = Socket.select(null, ss, null, 100.msecs);

         if (status > 0)
         {
             for (int j = 0; j < sockets.length; j++)
             {
                 if (sockets[j] !is null && ss.isSet(sockets[j]))
                 {
                     try {
                         
writeln(sockets[j].remoteAddress().toString());
                         ss.remove(sockets[j]);
                         sockets[j].close();
                         sockets[j] = null;
                     } catch {
                     }
                 }
             }
         }
         Thread.sleep(50.msecs);
     }
}



More information about the Digitalmars-d-learn mailing list