7

In PHP I just did: $fp = @fsockopen(irc.myserver.net, 6667, $errno, $errstr, 2);

Does Python 2.X also have a function like PHP's fsockopen()? If not how else can I check if a server on port 6667 is up or not?

Drago
  • 1,755
  • 3
  • 19
  • 30

1 Answers1

14

The socket module can be used to simply check if a port is open or not.

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('irc.myserver.net', 6667))
if result == 0:
   print "Port is open"
else:
   print "Port is not open"
Ahmad
  • 69,608
  • 17
  • 111
  • 137
maggick
  • 1,362
  • 13
  • 23
  • 1
    Is there also a way to set time out? I tried using `sock.settimeout(5)` above the `result = sock.connect_ex(('irc.myserver.net',6667))` but that doesn't seem to work. – Drago Oct 18 '16 at 12:36
  • 1
    @Drago Yes with an exception, see : http://stackoverflow.com/questions/11865685/handling-a-timeout-error-in-python-sockets – maggick Oct 18 '16 at 12:37