My setdefaulttimeout in python is not functioning

Need help, my setdefaulttimeout in python is not working. Please kindly help.

Please share your code so we can understand what you are doing.

@danpeters Just saying “it’s not working” does not give anyone any information to work from. Is there an error or exception? What is the error message? Or does it run, but give a different result than you expect? If so, in what specific way?

It’s generally impossible to speculate without:

  • some actual code. ideally a Minimal Reproducing Example (also make sure to use code formatting)
  • a detailed description of your expectations, and how the results differs from those expectations

Below is my python code. When I run it, the setdefulttimeout seems not to be working because the program does not give any output at all. Pls someone should kindly help me.
Thanks.


#!/usr/bin/python

import socket 

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(2)

host = input("Enter host: ")
port = int(input("Enter port: "))

def portscanner(port):
    if sock.connect((host,port)):
        print ("Port is closed.")
    else:
        print ("Port is open.")
portscanner(port)

Does this kind of thing work?

#!/usr/bin/python3

import socket

def portscanner(host, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.setdefaulttimeout(2)
    try:
        if sock.connect((host, port)):
            print(f"Port {port} is closed.")
        else:
            print(f"Port {port} is open.")
    except:
        print(f"Connection refused on port {port}")


host = input("Enter host: ")
for port in range(21, 81):
    portscanner(host, port)

Still no output.

Okay, well that scrip is working fine on my system, so maybe it’s more to do with your system, rather than an issue with Python, per se, so maybe it would be of help if you said what your system set-up is?

As a footnote: I’m running Python 3.6.9 on a Linux OS

To add:

Are you sure that the host is on-line and reachable?

I have this script that I use to check on a set range of IP addresses

import socket
import os

network_ip = ['192', '168', '1']
on_line = []
ping = ".".join(network_ip)

print("Starting ping scan...\n")
for host in range(1, 21):
    ip_address = '{}.{}'.format(ping, host)
    print(f"sending ping: {ip_address}")
    stream = os.popen(f'ping -c 2 {ip_address}')
    output = stream.read()
    if '0 received' in output:
        print(f"{ip_address} unreachable\n")
    else:
        print(f"{ip_address} reachable\n")
        on_line.append(ip_address)

print(f"Ping response from {len(on_line)} hosts:\n")
for ip in on_line:
    print(ip)
print("\nDone.\n")

… which you’ll need to customize so match your LAN


To add a little more…

Having done some testing, I can say that the socket.setdefaulttimeout() method is working on my system, in the script that I posted.

You create a socket that was a timeout of 0 then you set the default to 2.
That does not change the existing socket.

Either do this:

socket.setdefaulttimeout(2)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

or what I tend to do is set all the properties I need on the created sock
and not reply on defaults. But then I write code with lots of sockets
with different policy for behaviors.

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)

Thanks for the reply. After trying the options I got the message below:

image.png

Daniel Peter

If you do not want the timeout to cause the program to quit prematurely you have to handle the exception. Enclose your connect between try and except:

try:
    ... # put your sock.connect() here
except TimeoutError:
    ... # put your timeout handling here

Timeout happens when you receive no response from the target - neither positive (connection established) nor negative (connection rejected).