如何使用 python 在 ssl/tls 套接字连接中获取域的 IP

How to get the IP of a domain in ssl/tls socket connection using python

我需要记录TLS连接成功的域名IP地址。这是一个简化的代码:

import socket, ssl

context = ssl.SSLContext() 
context.verify_mode = ssl.CERT_NONE 
context.check_hostname = False 

mycipher = "DHE-RSA-AES128-SHA"
context.set_ciphers(mycipher) 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
domain = "google.com"
mySocket = context.wrap_socket(sock, server_hostname = domain) 
mySocket.connect((domain, 443))
mySocket.close()

如何获取IP,连接成功就获取IP。如果没有,我不想记录IP。

我发现一些函数可以在 TLS 会话中获取选定的 TLS 版本 version() 和选定的密码套件 cipher(),当连接成功时,它总是检索一个值。但是我没有找到关于获取 IP 的任何信息。我知道它们可能是不同的东西(版本和密码与 TLS 会话相关,IP 与连接相关)但我不想记录不成功的 TLS 连接的 IP。只有当连接成功时,我才想记录IP(例如,将其存储在一个变量中)。

IP 地址是 TCP/IP 属性,不是 TLS 地址。

因此您应该查看 socket 模块给出的内容。

例如你有:

socket.getpeername()

Return the remote address to which the socket is connected. 

This is useful to find out the port number of a remote IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.) On some systems this function is not supported.