Skip to content

Instantly share code, notes, and snippets.

@dawranliou
Created January 23, 2017 23:30
Show Gist options
  • Save dawranliou/ef134f3f8e443c0642efb8004de9cc0f to your computer and use it in GitHub Desktop.
Save dawranliou/ef134f3f8e443c0642efb8004de9cc0f to your computer and use it in GitHub Desktop.
Application pinger
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