Python socket Module
Example
Get hostname and IP address:
import socket
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
print(f'Hostname: {hostname}')
print(f'IP: {ip}')
Try it Yourself »
Definition and Usage
The socket module provides low-level networking interface for creating network connections.
Use it to create TCP/UDP clients and servers, establish network connections, or work with raw network protocols.
Members
| Member | Description |
|---|---|
| AF_INET | Address family for IPv4. |
| AF_INET6 | Address family for IPv6. |
| SOCK_DGRAM | Socket type for UDP. |
| SOCK_STREAM | Socket type for TCP. |
| create_connection() | Create a TCP connection to a remote host. |
| create_server() | Create a TCP server socket. |
| getaddrinfo() | Translate host/port to address info. |
| gethostbyname() | Translate hostname to IPv4 address. |
| gethostname() | Return the current hostname. |
| socket() | Create a new socket object. |
| socket.accept() | Accept a connection (returns new socket and address). |
| socket.bind() | Bind socket to an address. |
| socket.close() | Close the socket. |
| socket.connect() | Connect to a remote address. |
| socket.listen() | Enable server to accept connections. |
| socket.recv() | Receive data from the socket. |
| socket.send() | Send data to the socket. |