Created
January 23, 2017 23:30
-
-
Save dawranliou/ef134f3f8e443c0642efb8004de9cc0f to your computer and use it in GitHub Desktop.
Application pinger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
def ping(host, port): | |
"""A generator to ping a particular application. | |
Return True if the destination port is occupied | |
Example: | |
>>> # ping application at port 99 | |
>>> pinger = ping('127.0.0.1', 99) | |
>>> # When there's no application ruuning | |
>>> next(pinger) | |
False | |
>>> # When there's an application running | |
>>> next(pinger) | |
True | |
>>> # Or you can use it in a loop, just like a normal ping | |
>>> while True: | |
... print(next(pinger)) | |
... | |
True | |
True | |
True | |
""" | |
while True: | |
with socket.socket() as s: | |
try: | |
s.connect((host, port)) | |
yield True | |
except: | |
yield False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment