← All notes

Python ssl - wrap sockets with SSLContext and create_default_context

Answer: ssl.create_default_context() returns a new SSLContext object with default settings. This module provides some more Pythonic support for SSL on top of OpenSSL. Use wrap_socket on an existing Python socket.

Examples

import socket, ssl

hostname = "example.com"
context = ssl.create_default_context()
with socket.create_connection((hostname, 443), timeout=5) as raw:
    with context.wrap_socket(raw, server_hostname=hostname) as tls:
        print(tls.version(), tls.selected_alpn_protocol())
        tls.sendall(b"HEAD / HTTP/1.1\r\nHost: example.com\r\n\r\n")
        print(tls.recv(1024))

Rules

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, ssl - TLS/SSL wrapper for socket objects; python/cpython (GitHub), Lib/ssl.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, ssl - TLS/SSL wrapper for socket objects; python/cpython (GitHub), Lib/ssl.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.

Cite this

Permanent ID: iil:note:h8y5p5jp

iinventedlight. 2026. "Python ssl - wrap sockets with SSLContext and create_default_context." iinventedlight Library, iil:note:h8y5p5jp, version of 2026-11-18. https://iinventedlight.com/library/notes/python-ssl/. License: CC-BY-4.0.

@misc{iil_note_h8y5p5jp,
  author = {{iinventedlight}},
  title = {{Python ssl - wrap sockets with SSLContext and create\_default\_context}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/python-ssl/},
  note = {Permanent ID iil:note:h8y5p5jp. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-ssl.md.