How to Close a Socket in Python?

Estimated read time 1 min read

To close a socket in Python, you can use the close() method provided by the socket object. Here’s an example of how to close a socket:

import socket

# Create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to a server
s.connect(("example.com", 80))

# Use the socket...

# Close the socket
s.close()

In this example, a socket is created using socket.socket() with the appropriate address family (AF_INET for IPv4) and socket type (SOCK_STREAM for TCP). The socket is then connected to a server using connect().

After using the socket for communication or any other purpose, you can call the close() method to close the socket and release any associated system resources.

Closing the socket is important to ensure proper cleanup and prevent resource leaks. Once the socket is closed, you cannot use it for any further communication.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply