โดยเราจะนำ 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