Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update fork to 0.3.1 of master #1

Merged
merged 7 commits into from
Jul 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Or use the latest version from the master (if you are brave enough)::
$ pip install git+https://github.com/stellarbit/aioping

Using aioping
------------
-------------

There are 2 ways to use the library.

Expand All @@ -27,7 +27,9 @@ root is allowed to send ICMP packets:

import asyncio
import aioping
import logging

logging.basicConfig(level=logging.INFO) # or logging.DEBUG
loop = asyncio.get_event_loop()
loop.run_until_complete(aioping.verbose_ping("google.com"))

Expand All @@ -51,6 +53,23 @@ error:
loop = asyncio.get_event_loop()
loop.run_until_complete(do_ping("google.com"))

Methods
-------

``ping(dest_addr, timeout=10, family=None)``

- ``dest_addr`` - destination address, IPv4, IPv6 or hostname
- ``timeout`` - timeout in seconds (default: ``10``)
- ``family`` - family of resolved address - ``socket.AddressFamily.AF_INET`` for IPv4, ``socket.AddressFamily.AF_INET6``
for IPv6 or ``None`` if it doesn't matter (default: ``None``)

``verbose_ping(dest_addr, timeout=2, count=3, family=None)``

- ``dest_addr`` - destination address, IPv4, IPv6 or hostname
- ``timeout`` - timeout in seconds (default: ``2``)
- ``count`` - count of packets to send (default: ``3``)
- ``family`` - family of resolved address - ``socket.AddressFamily.AF_INET`` for IPv4, ``socket.AddressFamily.AF_INET6``
for IPv6 or ``None`` if it doesn't matter (default: ``None``)

Credits
-------
Expand All @@ -77,6 +96,7 @@ Credits
- https://github.com/nARN
- https://github.com/hergla
- https://github.com/hanieljgoertz
- https://github.com/Crypto-Spartan


License
Expand Down
25 changes: 14 additions & 11 deletions aioping/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,10 @@ async def receive_one_ping(my_socket, id_, timeout):
return time_received - time_sent

except asyncio.TimeoutError:
asyncio.get_event_loop().remove_writer(my_socket)
asyncio.get_event_loop().remove_reader(my_socket)
my_socket.close()

raise TimeoutError("Ping timeout")


Expand All @@ -190,7 +193,6 @@ def sendto_ready(packet, socket, future, dest):
future.set_result(None)



async def send_one_ping(my_socket, dest_addr, id_, timeout, family):
"""
Send one ping to the given >dest_addr<.
Expand All @@ -200,7 +202,6 @@ async def send_one_ping(my_socket, dest_addr, id_, timeout, family):
:param timeout:
:return:
"""

icmp_type = ICMP_ECHO_REQUEST if family == socket.AddressFamily.AF_INET\
else ICMP6_ECHO_REQUEST

Expand Down Expand Up @@ -230,25 +231,26 @@ async def send_one_ping(my_socket, dest_addr, id_, timeout, family):
await future


async def ping(dest_addr, timeout=10):
async def ping(dest_addr, timeout=10, family=None):
"""
Returns either the delay (in seconds) or raises an exception.
:param dest_addr:
:param timeout:
:param family:
"""

loop = asyncio.get_event_loop()
info = await loop.getaddrinfo(dest_addr, 0)

logger.debug("%s getaddrinfo result=%s", dest_addr, info)

# Choose one of the v4 IPs resolved by DNS
resolved = list(filter(
lambda i: i[0] == socket.AddressFamily.AF_INET and i[1] == socket.SocketKind.SOCK_DGRAM,
info
))
if family is not None:
info = list(filter(lambda i: i[0] == family, info))

if len(info) == 0:
raise socket.gaierror("%s hostname not found for address family %s" % (dest_addr, family))

resolved = random.choice(resolved)
resolved = random.choice(info)

family = resolved[0]
addr = resolved[4]
Expand Down Expand Up @@ -287,19 +289,20 @@ async def ping(dest_addr, timeout=10):
return delay


async def verbose_ping(dest_addr, timeout=2, count=3):
async def verbose_ping(dest_addr, timeout=2, count=3, family=None):
"""
Send >count< ping to >dest_addr< with the given >timeout< and display
the result.
:param dest_addr:
:param timeout:
:param count:
:param family:
"""
for i in range(count):
delay = None

try:
delay = await ping(dest_addr, timeout)
delay = await ping(dest_addr, timeout, family)
except TimeoutError as e:
logger.error("%s timed out after %ss" % (dest_addr, timeout))
except Exception as e:
Expand Down
24 changes: 16 additions & 8 deletions aioping/tests/test_aioping.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,40 @@
import asyncio
from aioping import verbose_ping, ping
import logging
import socket


class TestAioping(TestCase):
def __init__(self, methodName):
super().__init__(methodName)
logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.INFO)

def test_verbose_ping(self):
loop = asyncio.get_event_loop()

tasks = [
asyncio.ensure_future(verbose_ping("heise.de")),
asyncio.ensure_future(verbose_ping("google.com")),
asyncio.ensure_future(verbose_ping("a-test-url-taht-is-not-available.com")),
asyncio.ensure_future(verbose_ping("192.168.1.111"))
asyncio.ensure_future(verbose_ping("192.168.1.111")),
asyncio.ensure_future(verbose_ping("heise.de", family=socket.AddressFamily.AF_INET)),
asyncio.ensure_future(verbose_ping("google.com", family=socket.AddressFamily.AF_INET)),
asyncio.ensure_future(verbose_ping("heise.de", family=socket.AddressFamily.AF_INET6)),
asyncio.ensure_future(verbose_ping("google.com", family=socket.AddressFamily.AF_INET6))
]

loop.run_until_complete(asyncio.gather(*tasks))

async def _do_ping(self, host):
try:
delay = await ping(host) * 1000
print("Ping response from %s in %s ms" % (host, delay))
print("%s ping response in %0.4fms" % (host, delay))
except TimeoutError:
print("Timed out")
print("%s timed out" % host)

def test_ping(self):
def test_many_pings(self):
loop = asyncio.get_event_loop()
loop.run_until_complete(self._do_ping("192.168.0.255"))
tasks = []

for i in range(255):
tasks.append(asyncio.ensure_future(self._do_ping("192.168.0.%s" % i)))

loop.run_until_complete(asyncio.gather(*tasks))
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
setup(
name="aioping",
packages=["aioping"],
version="0.3.0",
version="0.3.1",
install_requires=["async_timeout", "aiodns"],
description="Asyncio ping implementation",
author="Anton Belousov",
author_email="anton@stellarbit.com",
url="https://github.com/stellarbit/aioping",
download_url="https://github.com/stellarbit/aioping/tarball/0.3.0",
download_url="https://github.com/stellarbit/aioping/tarball/0.3.1",
keywords=["network", "icmp", "ping", "asyncio"],
classifiers=[
"Development Status :: 4 - Beta",
Expand Down