Ethan Neidhart
Ethan Neidhart

Reputation: 75

How do I detect my wireless device using python?

I have a wireless device which I've been sending commands to remotely via a python script. More than one person may try to access it at a time, but this device allows only one TCP/IP connection at a time (which is a good thing for this application). What I want to do is let someone know that the device is in use already (they just get a generic error now, as if the device is down). I thought a good way to do this was, try to ping the device first. If the device is up but there is still no connection, it means someone else is connected. However, if I try to ping the device while someone else is connected, it acts as if the device is down. I've tried to see if there are any non-blocking settings on my device that I can alter (I'm new to wireless communication so I don't even know if that will help), but I'm getting nowhere with this. Is there a way to detect this device (given its IP address) without actually establishing a TCP connection? By the way, I'm running Windows 7 and my current code to ping the device looks like this:

def isUp(hostname):
    response = os.system("ping " + hostname + " -n 1")
    isUpBool = False
    if response == 0:
        print hostname, 'is up!'
        isUpBool = True
    else:
        print hostname, 'is down!'
    return isUpBool

Upvotes: 2

Views: 1579

Answers (2)

Ethan Neidhart
Ethan Neidhart

Reputation: 75

Messing around with python's socket library, I found a sort of roundabout way to solve this problem. Turns out, when you try to use my program on a device that's already in use, the error is triggered when you try to send or receive data (NOT when you connect to it). I had been connecting and immediately trying to communicate to determine if the connection existed, and when it didn't work it looked like I had never connected in the first place. So if you are able to successfully establish a connection, but not able to communicate, you can tell when there is an existing connection.

Upvotes: 0

greenMamBa
greenMamBa

Reputation: 165

Try this

import os

hostname = raw_input ('Enter the hostname: ')
response = os.system("ping -n 1 " + hostname)

if response == 0:
    print(hostname, 'is up!')
else:
    print(hostname, 'is down!')

Upvotes: 1

Related Questions