สามารถเช็ค check internet ด้วย python ได้
โพสต์แล้ว: 27/12/2018 11:44 am
ในบทความนี้ ได้นำภาษา python มาช่วยในการตรวจสอบการใช้งาน Internet หรือสัญญาณ wireless ที่เรากำลังเชื่อมต่ออยู่นั้นยังใช้งานได้อยู่หรือไม่ เพื่อให้สามารถตรวจสอบได้ว่าเป็นที่สัญญาณเครือข่าย เป็นที่สายอุปกรณ์ หรือจะเป็นที่ port ได้
โดยเราจะนำ library ของ python มาใช้ด้วยกัน 2 ตัวคือ socket และ urllib
# socket
จะมาเริ่มต้นที่ตัว socket ( library นี้มักจะมีอยู่กับ python แล้วไม่ต้องลงเพิ่ม)
เป็นที่เรียกใช้ function socket library และในวงเล็บจะเป็น (host ที่ต้องการทดสอบ,port)
ตัวอย่าง Code ทั้งหมดของ socket
# urllib
ต่อมาเป็นของตัว urllib ( library นี้มักจะมีอยู่กับ python แล้วไม่ต้องลงเพิ่ม)
ความหมายของ from...import... ซึ่งจะนำเอา function urlopen มาเรียกใช้งาน
เพื่อให้ทำการทดสอบโดยเปิด url ของ google
ตัวอย่าง Code ทั้งหมดของ urllib
ผลลัพท์ที่ได้ จากการทดสอบกรณีที่ ใช้งาน Internet ได้ปกติ
ผลลัพที่ได้ จากการทดสอบกรณีที่ ปิดการใช้งาน Internet
โดยเราจะนำ library ของ python มาใช้ด้วยกัน 2 ตัวคือ socket และ urllib
# socket
จะมาเริ่มต้นที่ตัว socket ( library นี้มักจะมีอยู่กับ python แล้วไม่ต้องลงเพิ่ม)
โค้ด: เลือกทั้งหมด
socket.create_connection(('www.google.com',80))
ตัวอย่าง Code ทั้งหมดของ socket
โค้ด: เลือกทั้งหมด
import socket
try:
print("checking internet connection")
socket.create_connection(('www.google.com',80))
status = "Connected"
print ('network is good')
except socket.error as msg:
status = "Not connected"
print ('there is no internet connection')
print (status)
ต่อมาเป็นของตัว urllib ( library นี้มักจะมีอยู่กับ python แล้วไม่ต้องลงเพิ่ม)
โค้ด: เลือกทั้งหมด
from urllib.request import urlopen
โค้ด: เลือกทั้งหมด
response = urlopen('http://google.com')
ตัวอย่าง Code ทั้งหมดของ urllib
โค้ด: เลือกทั้งหมด
from urllib.request import urlopen
try:
print("checking internet connection")
response = urlopen('http://google.com')
status = "Connected"
print ('network is good')
except urllib.URLError as err:
status = "Not connected"
print ('there is no internet connection')
print (status)
ผลลัพที่ได้ จากการทดสอบกรณีที่ ปิดการใช้งาน Internet