0

嗨,我正在编写一个脚本供用户输入 url。我应该验证 url 并让用户知道 url 是否有效。如果我故意输入错误的 url,我会收到 gaierror 的错误消息,但我已经输入了错误在这里处理代码,以便我的程序收到一条消息“无法连接”,就像正常退出一样。看起来像代码行“如果 sock 是 None:-print 'could not open socket' 没有在下面的程序中执行。我是新来的在套接字编程中。我想我做错了什么。有人可以在这里帮助我。在此先感谢!

#!/usr/bin/env python
import socket
import sys


def hello(c):
  t=c
  port = 80
  slash=t.split("/")
  basename="/".join(slash[2:3])
  pathname="/"+"/".join(slash[3:])
  sock=None

  for res in socket.getaddrinfo(basename, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
     af, socktype, proto, canonname, sa = res
     try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     except socket.error:
        sock= None
        continue
     try:
        sock.connect((basename, port))
     except socket.error:            
        sock= None
        continue

  if sock is None:
    print 'could not open socket'###I dont get this printed 
    sys.exit(0)   

  sock.send("HEAD %s HTTP/1.0\r\n\r\n" % pathname)
  l=sock.recv(12)
  return l
  sys.exit(1)
  sock.close()


``I call the hello function from here``
k= hello("https://mail.yah")`purposefully wrong to verify error handle
print k
newsplit=k.split()
print newsplit
insplit=eval(newsplit[1])
print insplit
if insplit==404:
 print "bad"
else:
 print "ok"

我收到以下错误消息:

 Traceback (most recent call last):
 File "C:/myserver/cgi-bin/domain.py", line 40, in <module>
 k= hello("https://mail.yah")
 "C:/myserver/cgi-bin/domain.py", line 13, in hello
 for res in socket.getaddrinfo(basename, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
 gaierror: [Errno 11004] getaddrinfo failed
4

1 回答 1

0

您可能希望将其包装socket.getaddrinfo(basename, port, socket.AF_UNSPEC, socket.SOCK_STREAM)try/except socket.gaierror块中,这应该可以解决问题:

try:
    for res in socket.getaddrinfo(basename, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
         af, socktype, proto, canonname, sa = res
         # stuff
except socket.gaierror:
    print 'getaddrinfo failed!'

确实,实际上是socket.getaddrinfo(basename, port, socket.AF_UNSPEC, socket.SOCK_STREAM)导致错误的原因!

于 2012-12-04T00:16:29.267 回答