使用套接字时语法无效

时间:2016-09-20 19:27:02

标签: python sockets

我对这段代码感到很挣扎,我不知道为什么它说第15行有语法错误。我试图用谷歌创建一个TCP连接,用于我的大学课程的诊断工具。

import socket 
import sys

#defining the port and host we wll be using to check the internet connection on.
remote_connection = "www.google.com" #google will automatically load balance the request to the uk servers.
port = 80

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
    print("The script has exited with error %s" %(err))

try:
    sockettest = socket.gethostbyname(remote_connection)
if socket.gaierror:
    # this means that the connection is possibly blocked by a firewall and we will tell the end user.
print("there was an error resolving the host, possibly a firewall issue") 
sys.exit()
elif socket.timeout:
    #the connection has timedout which probably means the internet is offline
print("Your internet connection is offline, please connect all cables, reboot any network equiptment and try again")
sys.exit()

# connecting to the server
s.connect((remote_connection,port))

print("Your internet connection is active and working correctly! \n\
I was able to connect to:", (remote_connection), "sucessfully")

1 个答案:

答案 0 :(得分:5)

没有except声明
try:
    sockettest = socket.gethostbyname(remote_connection)