I have a simple socket server by python
#!/usr/bin/python3 # This is server.py file
import socket
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 2115
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
msg = serversocket.recv(1024)
print (msg.decode('ascii'))
clientsocket.close()
I want to test this server by nc or telnet for example
telnet 127.0.0.1 2115
but causes error but when i try to connect by another socket program written in python. works well
When you do host = socket.gethostname()
, your host
is assigned to something like "MacBookPro.local"
. Then you bind your server to it at serversocket.bind((host, port))
. Thus your listening socket isn't bound to 127.0.0.1
, so the connection attempt from telnet gets refused.
Instead, try serversocket.bind('', port)
and re-run your server. This time, it should accept the telnet connection.