{ "cells": [ { "cell_type": "markdown", "id": "e84aa25d", "metadata": {}, "source": [ "### Ping in Python\n", "\n", "using system command \n", "```shell\n", "$ping -c 1 # on *nix macOS\n", "$ping -n 1 # on windows\n", "```\n", "we check the __shell return value__ to determine if it is pingable" ] }, { "cell_type": "code", "execution_count": 2, "id": "acc31e64", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "PING google.com (172.217.25.14) 56(84) bytes of data.\n", "64 bytes from hkg07s24-in-f14.1e100.net (172.217.25.14): icmp_seq=1 ttl=114 time=59.5 ms\n", "\n", "--- google.com ping statistics ---\n", "1 packets transmitted, 1 received, 0% packet loss, time 0ms\n", "rtt min/avg/max/mdev = 59.511/59.511/59.511/0.000 ms\n", "PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.\n", "64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.012 ms\n", "\n", "--- 127.0.0.1 ping statistics ---\n", "1 packets transmitted, 1 received, 0% packet loss, time 0ms\n", "rtt min/avg/max/mdev = 0.012/0.012/0.012/0.000 ms\n" ] }, { "data": { "text/plain": [ "True" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import platform\n", "import subprocess\n", "\n", "def ping(host:str)->bool:\n", " '''\n", " ping by system command\n", " @host: ip / hostname / domain name\n", " '''\n", " option = '-n' if platform.system().lower() == 'windows' else '-c'\n", " command = ['ping', option, '1', host]\n", " return subprocess.call(command) == 0\n", "\n", "# test it\n", "ping('google.com')\n", "ping('127.0.0.1')" ] }, { "cell_type": "code", "execution_count": null, "id": "4ef5b3e9", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }