Socket Connection Refused [Errno 111] - python

I am trying to implement a simple ftp with sockets using C (server side) and Python (client side). When the server code is compiled and run, the user enters a port number. The client then enters "localhost " when compiling. For some reason I am getting [Errno 111] on the client side when I run the code. It is saying that the issue is with my client.connect statement. I have tried using multiple different port numbers and it throws this same error:
flip1 ~/FTPClient 54% python ftpclientNew.py localhost 2500
Traceback (most recent call last):
File "ftpclientNew.py", line 86, in <module>
main()
File "ftpclientNew.py", line 27, in main
if client.connect((serverName, portNumber)) == None:
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused
Another weird thing is that this connection error was not happening when I ran this same code a few days ago. Has anyone experienced a problem like this? Any idea what might be causing this? Thanks!
Here is the client code:
import sys, posix, string
from socket import *
def main():
if len(sys.argv) < 3:
print "\nFormat: 'localhost' <port number>!\n"
return 0
buffer = ""
bufferSize = 500
serverName = "localhost"
fileBuffer = [10000]
if sys.argv[1] != serverName:
print "Incorrect Server Name! \n"
return 0
portNumber = int(sys.argv[2])
client = socket(AF_INET, SOCK_STREAM)
if client < 0:
print "Error Creating Socket!! \n"
return 0
if client.connect((serverName, portNumber)) == None:
print "Client Socket Created...\n"
print "Connecting to the server...\n"
print "Connected!\n"
##clientName = raw_input("Enter a file name: ")

Sometimes localhost isn't working on host
Change this
serverName = 127.0.0.1

Try to change the serverName variable to 127.0.0.1.

Related

Downloading a file from a server [duplicate]

Using Paramiko I am trying to establish a connection with a server, but that connection is failing with the following output
Traceback (most recent call last):
File "C:\ucatsScripts\cleanUcatsV2.py", line 13, in <module>
ssh.connect(host,username,password)
File "C:\Python27\lib\site-packages\paramiko-1.7.6-py2.7.egg\paramiko\client.py", line 278, in connect
for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
socket.gaierror: [Errno 10109] getaddrinfo failed
Here is the code I am using
import paramiko
import cmd
import sys
# Connect to Server
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
success = ssh.connect('MASKED',username='MASKED',password='MASKED')
if (success != True):
print "Connection Error"
sys.exit()
else:
print "Connection Established"
any ideas?
Just add the port after the host and you'll be set:
ssh.connect('MASKED', 22, username='MASKED',password='MASKED')
BTW, as robots.jpg said, the connect method doesn't return anything. Instead of returning values it triggers exceptions.
Here is a more complete example:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paramiko, os, string, pprint, socket, traceback, sys
time_out = 20 # Number of seconds for timeout
port = 22
pp = pprint.PrettyPrinter(indent=2)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
file = open( "file.txt", "r" )
# NOTE: The file contains:
# host user current_password
array = []
for line in file:
array = string.split(line.rstrip('\n'),)
# pp.pprint(array)
try:
ssh.connect(array[0], port, array[1], array[2], timeout=time_out)
print "Success!! -- Server: ", array[0], " Us: ", array[1]
except paramiko.AuthenticationException:
print "Authentication problem -- Server: ", array[0], " User: ", array[1]
continue
except socket.error, e:
print "Comunication problem -- Server: ", array[0], " User: ", array[1]
continue
ssh.close()
file.close()
The code needs some polish but it does the job.
Be care to didn't have the username on your hostname
ssh.connect(hostname='user#example.com', port=22)
user#example.com isn't a hostname parameter that fit for the connection.
You should use:
ssh.connect(hostname='example.com', port=22, username='user')
Are you sure the hostname resolves to IP address? Try ping that_hostname on your machine to see.
You need to make some changes for DNS.
Go to Network Connections -> IPv4-> Advanced Settings -> DNS then check Append these DNS suffixes, and enter your machine dns.
This worked for me. Anyway this error comes from the Ethernet settings.
Good Luck !

ConnectionRefusedError: [Errno 61] Connection refused Python3.8.5 on Mac

I'm trying to connect myself with 2 pythons little programs while using socket.
1st program:
#server.py
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1' #L'IP du Serveur
port = 1234 #data transfering port
server.bind((host,port)) #bind server
server.listen(5)
client, addr = server.accept()
print("Got Connection from",addr)
client.send("Hello World :)".encode('UTF-8')) #send data to client
msg = client.recv(1024)
print(msg.decode('UTF-8'))
input()
2nd program:
#client.py
import socket
server = socket.socket()
host = '127.0.0.1' #L'IP du Serveur
port = 1234
server.connect((host,port))
msg =server.recv(1024)
print(msg.decode('UTF-8'))
server.send('Client Online ...'.encode('UTF-8'))
input()
I first run server.py, no problems. Than, I run client.py but when I run it I have:
"
Traceback (most recent call last):
File "/Users/user/Documents/client.py", line 8, in <module>
server.connect((host,port))
ConnectionRefusedError: [Errno 61] Connection refused
>>>
"
I tried multiple things like desactivate my wall fire, put my 192.168.1.x IP but still have the same message error. I also send that to one of my friends that is on a PC (I'm on a MAC) and he has no problems. So I guess that the problem is because of the fact that I have a mac. Someone have an answer or an explanation ?
I was coding with IDLE. It was the problem. I guess that IDLE has a protection that doesn't allow people to do sockets. So I just went to Terminal and it finally works.

socket programming : tcp_client "gai" error

I'm setting up a simple client socket (my server socket works well). But I'm stuck by a lil bug. here's my code and here's the error. Can't find this error nowhere on the web.
from socket import *
import sys
host=socket.gethostname()
#host=127.0.0.1
serverPort= 12345
clientSocket =socket(AF_INET,SOCK_STREAM)
clientSocket.connect((127.0.0.1,serverPort))
msg= raw_input("Input text here:")
clientSocket.send(msg)
modmsg= clientSocket.recv(1024)
print "from server", modmsg
clientSocket.close()
the error:
Traceback (most recent call last):
File "tcp_client.py", line 5, in <module>
clientSocket.connect((serverName,serverPort))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno -5] No address associated with hostname
Your code is incorrect here (did you post the real code you ran?):
host cannot be empty
connect takes 1 argument and it's a tuple
if you do from socket import *, you cannot do socket.socket
fixed:
import socket
import sys
host=socket.gethostname()
serverPort= 12345
clientSocket = socket.socket(AF_INET,SOCK_STREAM)
clientSocket.connect((host,serverPort))
msg= raw_input("Input text here:")
clientSocket.send(msg)
modmsg= clientSocket.recv(1024)
print "from server", modmsg
clientSocket.close()
now I get proper timeout when I run this code (I don't have the client) instead of your error.

OSError: [WinError 10022] An invalid argument was supplied

Im making a port scanner it through's this message here is my code but it checks one port 21 i have pasted output below
import socket
import os
host = input("Enter the host name or ip : ")
s = socket.socket()
s.settimeout(5)
p = 0;
s.close
port = [21,22,23,25,53,80,110,115,135,139,143,194,443,445,1433,3306,3389,5632,5900,6112]
while(p<=19):
try:
s.connect(('host', port[p]))
except ConnectionRefusedError:
print("Port %d is close" %(port[p]))
except socket.timeout:
print("Port %d is close" %(port[p]))
else:
print("Port %d is open" %(port[p]))
p=p+1;
s.close
On command line :
PS E:\Codes by me\Selenium py> python .\practice.py
Enter the host name or ip : 89.86.98.76
Port 21 is close # it checks one port
Traceback (most recent call last):
File ".\practice.py", line 11, in <module>
s.connect((host, port[p]))
OSError: [WinError 10022] An invalid argument was supplied
You are passing the literal string 'host' as the host. You should be passing the variable host:
s.connect((host, port[p]))
You are also not actually closing the socket each time, since you left off the parentheses in s.close(). But if you did close the socket each time, you would have to create a new socket each time, instead of trying to reuse the same socket. You can't reuse a closed socket.

Prevent application from closing due to a 'connection refused' error

I am writing a Python client which connects with simple sockets in a server (also written in Python). I want to prevent client termination when the connection in server refused. In other words, I want to make client "search" for the server (if there is no connection) every 30 seconds.
Here is the code I wrote, but when the connection terminates from the server, the client returns an error for connection refused, and terminates itself.
Code:
#!/usr/bin/python
import socket
import time
while True:
sock = socket.socket()
host = socket.gethostname()
port = 4444
conn = sock.connect((host,port))
while(conn != None):
print 'Waiting for the server'
time.sleep(30)
sock = socket.socket()
host = socket.gethostname()
port = 4444
conn = sock.connect((host,port))
while True:
recv_buf = sock.recv(1024)
if (recv_buf == 'exit'):
break
print(recv_buf)
sock.send('hi server')
Error:
Traceback (most recent call last): File "s_client.py", line 12, in
conn = sock.connect((host,port)) File "C:\Program Files\python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args) socket.error: [Errno 10061] ─ίΊ ▐ΪάΊ ϊΫΊάΪ▐ ύ ϊύΉώΎΫ±ή▀ά ≤²Ίϊί≤ύ≥,
So any idea, that will help not to terminate the client, but to make it continuously look for the server, is welcome.
Use try-except:
conn = None
while(conn == None):
sock = socket.socket()
host = socket.gethostname()
port = 4444
try:
conn = sock.connect((host,port))
except:
print 'Waiting for the server'
time.sleep(30)
It's better to avoid the initial connect call and perform the connect only through the connect in the while loop. I have made a few other changes too, like moving the sleep call to the except part.

Categories

Resources