Checking if a port is listening
Lucien via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Mar 17 12:25:12 PDT 2016
On Wednesday, 16 March 2016 at 22:22:15 UTC, Anonymouse wrote:
> 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 ?
>
> I don't know if they apply here, but you can lower the send and
> receive timeouts for the socket. I'm not sure which (or if
> either) of them you want to tweak.
>
> https://dlang.org/library/std/socket/socket_option.html
>
>
> import core.thread; // for .seconds
> s.setOption(SocketOptionLevel.SOCKET, SNDTIMEO, 10.seconds);
> s.setOption(SocketOptionLevel.SOCKET, RCVTIMEO, 10.seconds);
>
>
> I guess you could also use a non-blocking socket and decide
> yourself when enough time has passed to declare it a failed
> attempt.
When it's non-blocking, all adresses have the open 22 open, but
it isn't the case..
When I setOption like you said, it's too long.
Is there a good technique ?
nmap can do it in only ~2 seconds.
My current code :
--------------------------------------------------------
import std.process;
import std.socket;
import core.time;
// ...
// 32 for the moment
for (int i = 1; i < 32; i++) {
string ip = "192.168.0."~to!string(i);
Socket s = new Socket(AddressFamily.INET,
std.socket.SocketType.STREAM, ProtocolType.TCP);
s.blocking = false;
//s.setOption(SocketOptionLevel.SOCKET,
SocketOption.SNDTIMEO, 1.seconds);
//s.setOption(SocketOptionLevel.SOCKET,
SocketOption.RCVTIMEO, 1.seconds);
InternetAddress ia = new InternetAddress(ip, 22);
try {
s.connect(ia);
writeln("\nDONE: ", ip, ":22");
} catch (Exception e) {
writeln("\n\nFAIL: ", ip, ":22 is unreachable :\n",
e.toString(), "\n");
}
s.close();
}
// ...
-------------------------------------
More information about the Digitalmars-d-learn
mailing list