liveBook · Manning

Socket.bind

As explained in Python Concurrency with asyncio

socket.bind is the socket operation that associates a socket with a local network address.

socket.bind associates a server socket with a local hostname and port, giving clients a network address to connect to. section 3.1

Use bind as part of the server setup sequence:

  • Create an IPv4 TCP socket with socket.AF_INET and socket.SOCK_STREAM. section 3.1
  • Bind the socket to an address such as ('127.0.0.1', 8000). section 3.1
  • Call listen, then accept connections arriving at the bound server socket. section 3.1

Bind a local TCP server

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_address = ('127.0.0.1', 8000) server_socket.bind(server_address) server_socket.listen() section 3.1

Figure 3.1 A client connects to our server socket. The server then creates a new socket to communicate with the client.
03-01

Visualizes the server socket as a main mailbox that accepts a client and provides a separate communication socket. section 3.1

How Python Concurrency with asyncio covers it

How deep it goes
Shows binding within a runnable TCP-server setup, then continues through listen and accept without explaining operating-system internals.
Examples
Uses a Python server socket bound to 127.0.0.1 on port 8000.
What it assumes
Assumes basic Python socket use while establishing address families, TCP sockets, and the server setup sequence.
What you can do after
Operate/configure a Python TCP server by assigning its local address before listening for connections.
How it connects
Connects sockets with TCP, hostnames, port numbers, listening, and accepting client connections.

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.