Check the Network Connection while Testing [ Please Help if possible ]

Hello All,

Hope everyone of you are safe and sound.

I am trying to do some testing and monitoring on a loop while making sure the internet connection is working. If the Internet connection is down, I want the script to be on a loop until it’s up again, and let me know the down time, up time and continue it’s work.

Being a self learned person I am not the best at it in basics. I try stuff, do stuff and check if they work :sweat: So please be kind enough to bare with me and help me out.

The below Script does a job of checking if the Network is available and be on loop until it’s back and let’s us know the connected time, down time, reconnected time and how long was it off. ( which I found on a website blog )

def main():
	# MAIN
	monitor_start_time = datetime.datetime.now()
	
	# monitoring time is when the script
	# started monitoring internet connection status
	monitoring_date_time = "monitoring started at: " + \
		str(monitor_start_time).split(".")[0]

	if first_check():
		# if true
		print(monitoring_date_time)
		
		# monitoring will only start when
		# the connection will be acquired

	else:
		# if false
		while True:
		
			# infinite loop to check if the connection is acquired
			# will run until there is a live internet connection
			if not ping():
			
				# if connection not acquired
				time.sleep(1)
			else:
			
				# if connection is acquired
				first_check()
				print(monitoring_date_time)
				break

			with open(FILE, "a") as file:
				# writes into the log file
				file.write("\n")
				file.write(monitoring_date_time + "\n")

	while True:
	
		# FIRST WHILE, infinite loop,
		# will run untill the machine is on
		# or the script is manually terminated
		if ping():
			# if true: the loop will execute after every 5 seconds
			time.sleep(5)

		else:
		
			# if false: fail message will be displayed
			down_time = datetime.datetime.now()
			fail_msg = "disconnected at: " + str(down_time).split(".")[0]
			print(fail_msg)

			with open(FILE, "a") as file:
				# writes into the log file
				file.write(fail_msg + "\n")

			while not ping():
				# infinite loop,
				# will run till ping() return true
				time.sleep(1)

			up_time = datetime.datetime.now()
			
			# will execute after while true is
			# false (connection restored)
			uptime_message = "connected again: " + str(up_time).split(".")[0]

			down_time = calculate_time(down_time, up_time)
			
			# calling time calculating
			# function, printing down time
			unavailablity_time = "connection was unavailable for: " + down_time

			print(uptime_message)
			print(unavailablity_time)

			with open(FILE, "a") as file:
				
				# log entry for connected restoration time,
				# and unavailability time
				file.write(uptime_message + "\n")
				file.write(unavailablity_time + "\n")

I took the above code and did something below, :sweat: :sweat: :sweat:

This part below is prior to the loop begins of testing,

FILE = os.path.join(os.getcwd(), "Network Log.log")

def ping():

    try:

        socket.setdefaulttimeout(3)

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        host = "8.8.8.8"

        port = 53

        server_address = (host, port)

        s.connect(server_address)

    except OSError as error:

        return False

    else:

        s.close()

        return True

def calculate_time(start, stop):

    difference = stop - start

    seconds = float(str(difference.total_seconds()))

    return str(datetime.timedelta(seconds=seconds)).split(".")[0]

def first_check():

    if ping():

        live = "\nCONNECTION ACQUIRED\n"

        print(live)

        connection_acquired_time = datetime.datetime.now()

        acquiring_message = "connection acquired at: " + \

            str(connection_acquired_time).split(".")[0]

        print(acquiring_message)

        with open(FILE, "a") as file:

            file.write(live)

            file.write(acquiring_message)

        return True

    else:

        not_live = "\nCONNECTION NOT ACQUIRED\n"

        print(not_live)

        with open(FILE, "a") as file:

            file.write(not_live)

        return False


first_check()

MY CODES TO : LOGIN

monitor_start_time = datetime.datetime.now()

monitoring_date_time = "monitoring started at: " + \

    str(monitor_start_time).split(".")[0]

Then the below inside a >>> for loop <<< which starts as :

        while True:

            if ping():

                time.sleep(3)

               MY CODES FOR : TESTING

            else:

                down_time = datetime.datetime.now()

                fail_msg = "disconnected at: " + str(down_time).split(".")[0]

                print(fail_msg)

                with open(FILE, "a") as file:

                    file.write(fail_msg + "\n")

                while not ping():

                    time.sleep(10)

                up_time = datetime.datetime.now()

                uptime_message = "connected again: " + str(up_time).split(".")[0]

                down_time = calculate_time(down_time, up_time)

                unavailablity_time = "connection was unavailable for: " + down_time

                print(uptime_message)

                print(unavailablity_time)

                with open(FILE, "a") as file:

                    file.write(uptime_message + "\n")

                    file.write(unavailablity_time + "\n")

My requirement has been that my testing works if the connection is available and stop the code as soon as possible if the connection is down until we reconnect.

the testing code runs for around like 30 seconds to maximum of 1 minute if that of any concern ( if monitoring and testing cannot work simultaneously )

The scrip currently starts and works for few seconds and after couple of loops or so throws the below errors,

(socket.timeout: timed out)

During handling of the above exception, another exception occurred:

(urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host=’’, port=): Read timed out. (read timeout=<object object at 0x0000025D197186F0>)

During handling of the above exception, another exception occurred:

Hello J.Rambo,
I don’t know much about sockets, but after look around internet and read the documentation, the error of socket.timeout it’s caused because you need to set a timeout

sock.settimeout(None)

The other exception could be memory or timeout by it self, i recommend you try to solve the first exception, and maybe the second one will be fixed too

Hello Gabriel,

Thank you very much for your helping hand.
Sure I will test it out brother.

Thanks a lot, have a great day. :heart_eyes:

1 Like

Bro, it worked. Thanks a lot man !!! Much Love. TC.

1 Like