如何退出正常麻烦的套接字错误处理

时间:2012-12-04 00:10:52

标签: python sockets

您好我正在编写一个脚本供用户输入url。我应该验证网址并让用户知道网址是否有效。如果我故意输入错误的网址,我会收到gaierror的错误消息,但我有把错误处理代码放在这里,以便我的程序得到一条消息“无法连接”就像一个优雅的退出。像代码行一样“如果袜子是无: -print'无法打开套接字'没有在下面的程序中执行。我是套接字编程的新手。我想我做错了什么。有人可以在这里帮助我。谢谢提前!

#!/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

1 个答案:

答案 0 :(得分: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)