Of course! In Python, getpeername() is a socket method that returns the address of the remote endpoint (the peer) that the socket is connected to.

This is a fundamental concept in network programming. Let's break it down with clear explanations and examples.
What is getpeername()?
getpeername() is called on a connected socket. It returns a tuple containing the IP address and port number of the machine on the other end of the connection.
The exact format of the tuple depends on the address family of the socket:
- For IPv4 (
socket.AF_INET), it returns a tuple:(ip_address, port).- Example:
('192.168.1.100', 54321)
- Example:
- For IPv6 (
socket.AF_INET6), it returns a tuple:(ip_address, port, flow_info, scope_id).- Example:
('::1', 8080, 0, 0)(where:1is the IPv6 loopback address)
- Example:
Key Requirements
You can only call getpeername() on a socket that is in a "connected" state. This means you must have successfully called one of the following methods first:

socket.connect(): For a client socket to connect to a server.socket.accept(): For a server socket to accept an incoming connection from a client.
Calling getpeername() on an unconnected socket will raise an error: OSError: [Errno 107] Transport endpoint is not connected.
Practical Examples
Let's look at a classic client-server example to see getpeername() in action.
The Server
The server will create a socket, bind it to an address, and listen for connections. When a client connects, accept() will return a new socket object specifically for that client connection. We will then call getpeername() on this new socket to see who connected.
# server.py
import socket
# Use a high port number (> 1024) to avoid needing root privileges
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on
print("--- Server Starting ---")
# 1. Create a socket object
# socket.AF_INET for IPv4
# socket.SOCK_STREAM for TCP
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# 2. Bind the socket to a specific network interface and port
s.bind((HOST, PORT))
# 3. Listen for incoming connections
# 5 is the number of unaccepted connections that the system will allow
# before refusing new connections.
s.listen()
print(f"Server listening on {HOST}:{PORT}")
# 4. Accept a connection
# conn is a NEW socket object for sending/receiving data
# addr is the address of the client that connected
conn, addr = s.accept()
# Now the socket 'conn' is connected to the client.
# Let's get the peer's name using getpeername().
peer_info = conn.getpeername()
print(f"--- Connection accepted! ---")
print(f"Client connected from: {peer_info}")
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
print(f"Received from client: {data.decode('utf-8')}")
# After the loop, the connection is closed automatically by the 'with' statement.
print(f"--- Connection from {peer_info} closed. ---")
print("--- Server Shutting Down ---")
The Client
The client will create a socket and connect to the server. Once connected, it can call getpeername() to see the address of the server it's connected to.
# client.py
import socket
import time
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
print("--- Client Starting ---")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# Connect to the server
s.connect((HOST, PORT))
# The socket 's' is now connected to the server.
# Let's get the peer's name using getpeername().
peer_info = s.getpeername()
print(f"--- Connection established! ---")
print(f"Connected to server at: {peer_info}")
with s:
# Send some data to the server
message = "Hello, Server!"
print(f"Sending to server: {message}")
s.sendall(message.encode('utf-8'))
# Receive data from the server
data = s.recv(1024)
print(f"Received from server: {data.decode('utf-8')}")
# Wait a moment before closing
time.sleep(1)
print("--- Client Shutting Down ---")
How to Run and See the Output
-
Save the code above as
server.pyandclient.py. -
Open two separate terminal windows.
-
In the first terminal, run the server:
python server.py
You will see:
--- Server Starting --- Server listening on 127.0.0.1:65432 -
In the second terminal, run the client:
python client.py
You will see the client's output:
--- Client Starting --- --- Connection established! --- Connected to server at: ('127.0.0.1', 65432) Sending to server: Hello, Server! Received from server: Hello, Server! --- Client Shutting Down --- -
Now, look back at the server's terminal. It will show:
--- Server Starting --- Server listening on 127.0.0.1:65432 --- Connection accepted! --- Client connected from: ('127.0.0.1', 54321) # Note the different port! Connected by ('127.0.0.1', 54321) Received from client: Hello, Server! --- Connection from ('127.0.0.1', 54321) closed. --- --- Server Shutting Down ---
Key Observations from the Example
- Server's Perspective: The server's listening socket is bound to
('127.0.0.1', 65432). When the client connects from('127.0.0.1', 54321), theconn.getpeername()call on the server correctly identifies the client's address. - Client's Perspective: The client's socket connects to
('127.0.0.1', 65432). Thes.getpeername()call on the client correctly identifies the server's address it is connected to. - Dynamic Ports: Notice the client's port is a high number (e.g.,
54321). This is because the operating system assigns a temporary, ephemeral port for the client side of the connection.
The Opposite: getsockname()
It's helpful to contrast getpeername() with getsockname().
| Method | What it Returns | Purpose |
|---|---|---|
getpeername() |
The address of the remote machine you are connected to. | "Who am I talking to?" |
getsockname() |
The address of the local endpoint of this socket. | "What is my own address/port for this connection?" |
You can modify the server example to also print getsockname():
# Inside the 'with conn:' block in server.py
local_info = conn.getsockname()
peer_info = conn.getpeername()
print(f"Local socket address: {local_info}")
print(f"Peer (client) address: {peer_info}")
Output would look like this:
--- Connection accepted! ---
Local socket address: ('127.0.0.1', 65432)
Peer (client) address: ('127.0.0.1', 54321)
This clearly shows the local address is the server's well-known port, while the peer address is the client's temporary port.
