I am trying to learn how to use sockets using this tutorial:
https://www.tutorialspoint.com/python/python_networking.htm
I have copied the code from the site into my directory and ran it exactly as was done in the tutorial but got errors. Here is the code from the tutorial.
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print("asdf")
c.send('Thank you for connecting')
c.close() # Close the connection
and client.py
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
These are the console commands I ran:
python server.py &
python client.py
I got this errors after running the command:
Traceback (most recent call last):
File "client.py", line 9, in <module>
s.connect((host, port))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/soc ket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
In case this is helpful, the version of python I am using is Python 2.7.10 and I use a mac that is version 10.12.6
Thanks in advance
From the docs of socket.gethostname
:
Return a string containing the hostname of the machine where the Python interpreter is currently executing.
Note:
gethostname()
doesn’t always return the fully qualified domain name; usegetfqdn()
for that.
The host IP is not the same as the hostname. You have a couple of options:
You can either manually assign host
to 0.0.0.0
or localhost
You can also query socket.gethostbyname
:
host = socket.gethostbyname(socket.gethostname()) # or socket.getfqdn() if the former doesn't work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With