Search code examples
pythonwindowspython-3.xwin32com

Network checker giving false negatives python


This code is able to detect whether the internet is disconnected or connected, and works mostly as I've tested it. The problem is occasionally it says internet disconnected and right after that it says internet connected. This has happened many times while I'm browsing the web, watching videos or whatever, the point being I know the internet is working.

I know the code's a bit of a mess. What's causing these false disconnects?

import win32com.client as w
import socket
s = w.Dispatch("SAPI.SpVoice")
try:
    socket.setdefaulttimeout(5)
    socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(("8.8.8.8", 53))
    a = True
except Exception:
    a = False
    pass

while a == True:
    while True:
        try:
            socket.setdefaulttimeout(5)
            socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(("8.8.8.8", 53))
            s.Speak("Internet connected")
            break
        except Exception:
            continue
    while True:
        try:
            socket.setdefaulttimeout(5)
            socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(("8.8.8.8", 53))
            continue
        except Exception:
            s.Speak("Internet disconnected")
            break

while a == False:
    while True:
        try:
            socket.setdefaulttimeout(5)
            socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(("8.8.8.8", 53))
            continue
        except Exception:
            s.Speak("Internet disconnected")
            break
    while True:
        try:
            socket.setdefaulttimeout(5)
            socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(("8.8.8.8", 53))
            s.Speak("Internet connected")
        except Exception:
            continue

Solution

  • You're connecting to google's DNS server at a rate of about 100 times per second, at least on my machine. I wouldn't be surprised if they occasionally refuse your connections, but I'm not willing to test this theory. Perhaps your machine is running out of ports at this rate? I have no idea how windows TCP stack would handle something like this.

    Try adding a sleep into all of your loops to make sure you're not hammering them - testing your connection every couple of seconds should be fine.

    Also, your original question is "Why is the socket failing to connect?" Well, catch the exception, and print so you'll know (or say it out loud :) )