I keep getting this error
[Errno 10061] No connection could be made because the target machine actively refused it.
I'm running Windows 7 64 bit, no virus or protection software, and python is allowed through my firewall (I've also tried turning my firewall completely off but same result). When I run the server and use telnet it connects just fine. When I try to connect to the server with the client it fails. Any suggestions as to what I could try to fix this? If you need more information just ask and I'll provide.
Client Code
import socket
import sys
def main():
host = ""
port = 8934
message = "Hello World!"
host = raw_input("Enter IP: ")
#Create Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print "Failed to create socket. Error code: %s Error Message: %s"%(str(msg[0]),msg[1])
sys.exit()
print "Socket created"
#Connec to Server
print host
print port
s.connect((host,port))
print "You are connected to %s with IP adress of %s"%(host,host)
#Send Data
try:
s.sendall(message)
except socket.error:
print "Failed to send."
#Receive Data
reply = s.recv(4096)
if __name__ == "__main__":
main()
Server Code
# !usr/bin/python
import socket
import sys
HOST = ""
PORT = 8934
def main():
#Setup socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error,msg:
print "Unable to create socket"
sys.exit()
print "Socket created."
#Bind to adress
try:
s.bind((HOST,PORT))
except socket.error,msg:
print "Bind failed. Closing..."
sys.exit()
print "Socket bound."
#Start listening
s.listen(10)
print "Socket Listening"
#Accept connection
conn, addr = s.accept()
print "Connected to %s:%s"%(addr[0],addr[1])
if __name__ == "__main__":
main()
Taking a guess at your indentation, and running your codeā¦ it works just fine.* (As long as I type in 127.0.0.1 when it asks me for the IP.)
Of course the second time I run the client (if I haven't restarted the server) I get a connection-refused error. But that's just because you've coded a server that immediately quits as soon as it gets the first connection. So the second time you run the client, there is no server, so the OS rejects the connection.
You can always run the server again, which lets you run the client one more time. (Except that the server may get a 10048 error when it tries to bind the socket, because the OS is keeping it around for the previous owner. If you see that, look at SO_REUSEADDR in the docs.)
* By "works just fine" I mean that it connects, and prints out the following before quitting:
Socket created
127.0.0.1
8934
You are connected to 127.0.0.1 with IP adress of 127.0.0.1
Obviously it never sends anything to the server or receives anything back, because the server has no send or recv calls, or anything else.
Related
This is the client
from socket import *
import sys
clientsocket = socket(AF_INET, SOCK_STREAM)
host = "localhost"
port = 10000
message = "Hello"
try:
clientsocket.connect((host,port))
except Exception as data:
print (Exception,":",data)
print ("try again.\r\n")
sys.exit(0)
clientsocket.send(message.encode())
print(message.encode())
response = clientsocket.recv(1024)
print (response)
clientsocket.close()
This is the server
from socket import *
import time
client_facing_port = 10000
router_client_socket = socket(AF_INET, SOCK_STREAM)
router_client_socket.bind(("localhost", client_facing_port))
print ('the router is up on port:',client_facing_port)
router_client_socket.listen(0);
while True:
print ('Ready to serve...')
connectionSocket, addr = router_client_socket.accept()
print(router_client_socket.accept())
try:
message = connectionSocket.recv(1024)
if len(message.split())>0:
print (message,'::',message.split()[0])
connectionSocket.send("Hello to you too".encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
except IOError:
connectionSocket.send("something went wrong")
connectionSocket.close()
router_client_socket.close()
connectionSocket.close()
Very basic, I'm just trying to understand how sockets work in python.
Here's the problem, if I fire up the server the console prints
the router is up on port: 10000
Ready to serve...
and when I start the client its console prints
b'Hello'
basically the server gets stuck on connectionSocket, addr = router_client_socket.accept()
here's what I don't get, if I fire up a second client the console (of the second client) reads
ConnectionResetError: [WinError 10054] An existing connection was
forcibly closed by the remote host
which makes sense because the server is not multithread and can only handle one client at any given time since I used router_client_socket.listen(0), but the transaction between the first client and the server gets unstuck and completed! The first client receives the "hello to you too" message and prints it out.
What's causing this?
this is on python 3.9 using Spyder on Anaconda
I'm trying to code a port scanner in python with banner grabbing.
Without the s.send('getBanner\n') line (which grabs the banner) my script works, and it prints the open ports.
But when I add the 'getBanner' line, a socket error says '[Errn 32] Broken Pipe'.
I know that this error probably happens because the clients don't wait till the connection get established and close the socket. How can I solve this?
The code:
import socket
host = '192.168.1.1'
for port in range(1,1024):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.send(('getBanner\n'))
banner = s.recv(1024)
if result == 0:
print "[+] Port %s tcp/open" % port
print "[+] Banner: %s" % banner
s.close()
Not all ports have a service listening on them and when they do, you need to follow whatever protocol is normal for that service. I assume you have some sort of service that responds to "getBanner", but most will not. You are connecting to things like FTP, SSH, DNS, NFS and mail servers and these things don't have "getBanner" commands. But you are also trying to connect to ports that don't have anything listening on them and this generates an error.
Looking at the docs:
connect_ex(...)
connect_ex(address) -> errno
This is like connect(address), but returns an error code (the errno value)
instead of raising an exception when an error occurs.
Your connection call is returning an error code and you need to check that before trying to send the request. So, as a minimum:
import socket
host = '192.168.1.1'
for port in range(1,1024):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
if result == 0:
s.send(('getBanner\n'))
banner = s.recv(1024)
if result == 0:
print "[+] Port %s tcp/open" % port
print "[+] Banner: %s" % banner
s.close()
But since most servers listening on ports don't respond to a "getBanner" command, its either going to hang or more likely raise connection reset errors.
Ive seen similar questions but they I couldn't fix this error. Me and my friend are making a chat program but we keep getting the error
ConnectionRefusedError: [Errno 61] Connection refused
We are on different networks by the way.
Here is my code for the server
import socket
def socket_create():
try:
global host
global port
global s
host = ''
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error" + str(msg))
#Wait for client, Connect socket and port
def socket_bind():
try:
global host
global port
global s
print("Binding socket to port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket binding error" + str(msg) + "\n" + "Retrying...")
socket_bind
#Accept connections (Establishes connection with client) socket has to be listining
def socket_accept():
conn, address = s.accept()
print("Connection is established |" + " IP:" + str(address[0]) + "| port:" + str(address[1]))
chat_send(conn)
def chat_send(conn):
while True:
chat =input()
if len(str.encode(chat)) > 0:
conn.send(str.encode(chat))
client_response = str(conn.recv(1024), "utf-8")
print(client_response)
def main():
socket_create()
socket_bind()
socket_accept()
main()
And my client code
import socket
#connects to server
s = socket.socket()
host = '127.0.0.1'
port = 9999
s.connect((host, port))
#gets chat
while True:
data = s.recv(1024)
print (data[:].decode("utf-8"))
chat = input()
s.send(str.encode(chat))
This may not answer your original question, but I encountered this error and it was simply that I had not starting the server process first to listen to localhost (127.0.0.1) on the port I chose to test on. In order for the client to connect to localhost, a server must be listening on localhost.
'127.0.0.1' means local computer - so client connents with server on the same computer. Client have to use IP from server - like 192.168.0.1.
Check on server:
on Windows (in cmd.exe)
ipconfig
on Linux (in console)
ifconfig
But if you are in different networks then it may not work. ipconfig/ifconfig returns local IP (like 192.168.0.1) which is visible only in local network. Then you may need external IP and setting (redirections) on your and provider routers. External IP can be IP of your router or provider router. You can see your external IP when you visit pages like this http://httpbin.org/ip . But it can still need some work nad it be bigger problem.
You need simply to start server at first, and then run the client_code.
In VS Code i've opened 2 terminals. One for the server_code to be running While True, and the other one for the client_code
So this may not fix your question specifically but it fixed mine and it can help someone else I work with vscode and I use some extension that runs my code so when you want to run your server run it on your CMD or Terminal and run your client in vscode it helped me (maybe importat I work on mac so maybe spesific OS problem)
If you are connecting to a host:port that is open but there is no service bound to it you may see this IIRC. Eg with ssh you sometimes see this while attempting to connect to a server that is booting but sshd is not running.
This Code Not Valid For Chatting, you have to use unblocking sockets and select module or other async modules
I have begun learning Socket Programming and Issue I faced is. I am unable to connect Sockets when On two different network ( To be specific : I am using Web-host and Cgi programming to create python socket Server and my goal is to connect to that socket using desktop client python application )
My Server Coad : Location Public_html/cgi-bin/serverSocket.py
#!/usr/bin/python
print "Content-type: text/html\n\n";
import cgitb
import socket
cgitb.enable()
def main():
host = 'localhost'
port = 8111
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((host,port))
except socket.error as e:
print(str(e))
s.listen(10)
c,addr = s.accept()
print("Connection From : " + str(addr))
while True:
data = c.recv(1024)
if not data:
break
print ("From Connected user : " + str(data.decode()))
data =str(data.decode()).upper()
print ("sending :" + str(data))
c.send(data.encode())
if __name__ == '__main__':
main()
And Client Program : Location On My Local Computer C:/Desktop
#!/usr/bin/python
print "Content-type: text/html\n\n";
#Client Socket Program
import socket
def main():
host = 'www.mywebsite.com'
port = 8111
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host,port))
except socket.error as e:
print(str(e))
message=input("-> ")
while message != 'q':
s.send(message.encode())
print("Sent Message")
data=s.recv(1024)
print('Recieved from server :', str (data.decode()))
message=input("->")
s.close()
if __name__ == '__main__':
main()
| Error Encountered is : [WinError 10060] |
| Python Server uses : Python 2.6.6 |
| Python Client :python 3.4 |
While using This On same system (ie: Local host as Server and client works Fine)
PS: Also link if there is any tutorial on this,Also advice some configuration if must be made.
If you want them to access each other, use public IPs. (Public IP Address) You would also need to port-forward (this is different for every router so I can't explain, look it up). Otherwise, the port you want to access will not be accessible from other networks. When you port-forward, that port on your Public IP Address can then be accessed.
Python 2 and 3 handle sockets differently! See here this question for example. What you could do as a quick workaround is to change your client start line to "#!/usr/bin/env python2.7" to force the client to use python 2 as well, that should fix your problem.
I am trying to set up a local server so that other PCs on the same local network can connect to it. When trying to do so, on the client side, I get the following error:
[Errno 10061] No connection could be made because the target machine actively refused it
I have been searching around for hours and still couldn't resolve this issue. I tried turning off my Firewall too, but nothing.
These are my server and client codes:
Server Code:
import socket
import threading
import SocketServer
import datetime
ver_codes = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
print threading.current_thread().isDaemon()
data = self.request.recv(1024)
command = data.split()[0]
if(command=="login"):
if(logged_in(data.split()[1])==False):
self.request.sendall(login(data.split()[1], data.split()[2]))
else:
self.request.sendall("already in")
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def client(ip, port, message):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
sock.sendall(message)
response = sock.recv(1024)
print "Received: {}".format(response)
finally:
sock.close()
def logged_in(id_num):
for i in ver_codes:
if(i[0]==id_num):
return True
return False
def login(username, password):
login_file = open("Login.txt", "r")
match = login_file.readline()
while(match!="*"):
if(match.split()[0]==username):
if(match.split()[1]==password):
ver_codes.append([match.split()[0], encryption_code(match.split()[2])])
login_file.close()
return "{} {}".format(match.split()[2], encryption_code(match.split()[2]))
print "And Here"
match = login_file.readline()
return "Denied"
login_file.close()
def encryption_code(to_encrypt):
now = datetime.datetime.now()
return int(str(now.microsecond)) * int(to_encrypt)
if __name__ == "__main__":
HOST, PORT = "localhost", 7274
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
print server.server_address
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = False
server_thread.start()
print "Server loop running in thread:", server_thread.name
Client Code:
import socket
import sys
HOST, PORT = "localhost", 7274
data = " ".join(sys.argv[1:])
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
sock.sendall("login mahdiNolan m1373")
received = sock.recv(1024)
finally:
sock.close()
I really appreciate any help you could give me!
Thanks A LOT beforehand!
Your issue is because you're listening on localhost - this will only accept connections from the local machine.
If you want to accept connections from anywhere, instead of "localhost" just pass the empty string "". This is equivalent to specifying INADDR_ANY to the C sockets API - see the ip man page for more information, or this page also looks like it has some useful explanation. In short, this means "accept connections on any local interface".
Instead of the empty string you can instead specify an IP address of a local interface to only accept connections on that interface - it's unlikely you need to do this unless you machine has multiple network cards inside it (e.g. acting as a gateway) and you only want to serve requests on one of the networks.
Also, on the client side you should use the actual address of the machine - replace "localhost" with the IP address or hostname of the server machine. For example, something like "192.168.0.99". If you want to find the IP address of the server under Windows, open a DOS window and run the ipconfig command, look for the line with IPv4 Address (assuming you've got an IPv4 network which is very likely).
The Windows firewall will also block the server from accepting connections as you've already found, but you shouldn't need to disable it - as soon as you run your server you should see a popup window where you can instruct it to accept connections (that was on Windows 7, it might be different on other versions). In any case, turning the software firewall off should allow everything to work, although whether that's a security risk is a matter outside of the scope of this question.