title: Python SSL certificate check hostname according to common name
body: <p>I want to check if an hostname and a port according to a SSL certificate. I created this function :</p>
  
  <pre><code>@staticmethod
  def common_name_check(hostname, port):
      try:
          ctx = ssl.create_default_context()
          s = ctx.wrap_socket(socket.socket(), server_hostname=hostname)
          s.connect((hostname, int(port)))
          cert = s.getpeercert()
          ssl.match_hostname(cert, hostname)
      except Exception as e:
          exc_type, exc_obj, exc_tb = sys.exc_info()
          fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
          print(exc_type, fname, exc_tb.tb_lineno)
          return False
      else:
          return True
  </code></pre>
  
  <p>My problem is : When a certificate is expired the verification failed. But the exception is ambiguous : </p>
  
  <pre><code>&lt;class 'ssl.SSLError'&gt;
  </code></pre>
  
  <p>I can't know if error is due to certificate expired or bad common name</p>
  
  <p>How can I only check if hostname/port is valid for certificate ?</p>