22a5417
diff --git a/Modules/_ssl.c b/Modules/_ssl.c
22a5417
index df8c6a7d96d8..e8cffef14de0 100644
22a5417
--- a/Modules/_ssl.c
22a5417
+++ b/Modules/_ssl.c
22a5417
@@ -55,6 +55,11 @@ static PySocketModule_APIObject PySocketModule;
22a5417
 #include <sys/poll.h>
22a5417
 #endif
22a5417
 
22a5417
+#ifndef MS_WINDOWS
22a5417
+/* inet_pton */
22a5417
+#include <arpa/inet.h>
22a5417
+#endif
22a5417
+
22a5417
 /* Don't warn about deprecated functions */
22a5417
 #ifdef __GNUC__
22a5417
 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
22a5417
@@ -667,8 +672,41 @@ newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
22a5417
     SSL_set_mode(self->ssl, mode);
22a5417
 
22a5417
 #if HAVE_SNI
22a5417
-    if (server_hostname != NULL)
22a5417
-        SSL_set_tlsext_host_name(self->ssl, server_hostname);
22a5417
+    if (server_hostname != NULL) {
22a5417
+/* Don't send SNI for IP addresses. We cannot simply use inet_aton() and
22a5417
+ * inet_pton() here. inet_aton() may be linked weakly and inet_pton() isn't
22a5417
+ * available on all platforms. Use OpenSSL's IP address parser. It's
22a5417
+ * available since 1.0.2 and LibreSSL since at least 2.3.0. */
22a5417
+        int send_sni = 1;
22a5417
+#if OPENSSL_VERSION_NUMBER >= 0x10200000L
22a5417
+        ASN1_OCTET_STRING *ip = a2i_IPADDRESS(server_hostname);
22a5417
+        if (ip == NULL) {
22a5417
+            send_sni = 1;
22a5417
+            ERR_clear_error();
22a5417
+        } else {
22a5417
+            send_sni = 0;
22a5417
+            ASN1_OCTET_STRING_free(ip);
22a5417
+        }
22a5417
+#elif defined(HAVE_INET_PTON)
22a5417
+#ifdef ENABLE_IPV6
22a5417
+        char packed[Py_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
22a5417
+#else
22a5417
+        char packed[sizeof(struct in_addr)];
22a5417
+#endif /* ENABLE_IPV6 */
22a5417
+        if (inet_pton(AF_INET, server_hostname, packed)) {
22a5417
+            send_sni = 0;
22a5417
+#ifdef ENABLE_IPV6
22a5417
+        } else if(inet_pton(AF_INET6, server_hostname, packed)) {
22a5417
+            send_sni = 0;
22a5417
+#endif /* ENABLE_IPV6 */
22a5417
+        } else {
22a5417
+            send_sni = 1;
22a5417
+        }
22a5417
+#endif /* HAVE_INET_PTON */
22a5417
+        if (send_sni) {
22a5417
+            SSL_set_tlsext_host_name(self->ssl, server_hostname);
22a5417
+        }
22a5417
+    }
22a5417
 #endif
22a5417
 
22a5417
     /* If the socket is in non-blocking mode or timeout mode, set the BIO