Python 3.6 Socket绑定报错:nodename nor servname provided, or not known
socket.gaierror When Binding a Socket in Python 3.6 Hey there! I see you're working on your first Python socket messaging program and ran into a bind error—let's break this down and fix it.
First, let's recap your code and the error you're seeing:
Your Code:
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print(s) host = socket.gethostname() print(host) port = 8140 print(port) s.bind((host, port))
The Error:
<socket.socket fd=7, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('0.0.0.0', 0)> R1shinerg 8140 Traceback (most recent call last): File "/Users/g.shiner21/Desktop/Python/P2PFile/P2PFile2.py", line 12, in <module> s.bind((host, port)) socket.gaierror: [Errno 8] nodename nor servname provided, or not known
What's Causing This?
The error pops up because socket.gethostname() returns your machine's hostname (R1shinerg), but your system can't resolve this hostname to a valid IP address. This is a common hiccup when the hostname isn't properly mapped in your system's hosts file.
Solutions to Try:
1. Bind to 0.0.0.0 (Listen on All Interfaces)
If you want your program to accept connections from any device on your network (or just need a quick test fix), replace the host assignment with '0.0.0.0'. This tells the socket to listen on all available network interfaces:
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print(s) host = '0.0.0.0' # Updated this line print(host) port = 8140 print(port) s.bind((host, port))
2. Bind to the Local Loopback (127.0.0.1)
If you're only testing locally (no need for external devices to connect), use the loopback address. This is more secure for local-only testing:
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print(s) host = '127.0.0.1' # Updated this line print(host) port = 8140 print(port) s.bind((host, port))
3. Fix Hostname Resolution
If you want to keep using your hostname, add a mapping in your system's hosts file:
- On macOS/Linux: Open
/etc/hostswith a text editor (you’ll need sudo privileges) and add this line:127.0.0.1 R1shinerg - On Windows: Open
C:\Windows\System32\drivers\etc\hostsas Administrator and add the same line above.
After saving the file, your system will resolve R1shinerg to 127.0.0.1, and your original code should work as expected.
Give these a shot—any of them should clear up that gaierror for you!
内容的提问来源于stack exchange,提问作者gman1230321

