socket programming : tcp_client "gai" error - python

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.

Related

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.

OSError: [Errno 22] invalid argument socket python socket

I have some app that use UDP socket. Each app can to send and receive date.
In an app that recevie data, code is below:
receiver app:
UDPSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
bufferSize= 1024
EnginePort=2000
def ReceiveSocket():
global UDPSocket
global AddressPort
global bufferSize
AddressPort = ("127.0.0.2", EnginePort)
# Bind to address and ip
UDPSocket.bind(AddressPort)
print("UDP server up and listening")
bytesAddressPair = UDPSocket.recvfrom(bufferSize)
message = pickle.loads(bytesAddressPair[0])
address = bytesAddressPair[1]
clientMsg = "Message from Client:{}".format(message)
clientIP = "Client IP Address:{}".format(address)
print(clientMsg)
print(clientIP)
while True:
ReceiveSocket()
sending a simple message:
import socket
import pickle
UDP_IP = "127.0.0.2"
UDP_PORT = 2000
MESSAGE = "Hello, World!"
print ("UDP target IP:", UDP_IP)
print ("UDP target port:", UDP_PORT)
print ("message:", MESSAGE)
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
sock.sendto(pickle.dumps(MESSAGE), (UDP_IP, UDP_PORT))
When receive data ,give me this error:
receiver output:
Message from Client:Hello, World!
Client IP Address:('127.0.0.2', 2003)
Traceback (most recent call last):
File "/home/pi/RoomServerTestApps/Engine.py", line 88, in <module>
ReceiveSocket()
File "/home/pi/RoomServerTestApps/Engine.py", line 29, in ReceiveSocket
UDPSocket.bind(AddressPort)
OSError: [Errno 22] Invalid argument
But when the ReceiveSocket() is outside the while true(), app work well.
Please help me about this.
Thanks.
Get bind() out of the loop. You've already bound to the port at first run, that's why the second+ run fails.
AddressPort = ("127.0.0.2", EnginePort)
UDPSocket.bind(AddressPort)
def ReceiveSocket():
...

Python Web Server socket

I have to create a web server in Python. Below is the code I am working on. When i execute it, I initially get no error and it prints "Ready to serve.." , but after opening a browser and running http://10.1.10.187:50997/HelloWorld.html (HelloWorld is an html file in the same folder as my python code, while 10.1.10.187 is my IP address and 50997) is the server port), I get a TypeError saying 'a bytes like object is required and not str". please help me in resolving this and kindly let me know if any other modifications are required.
#Import socket module
from socket import *
#Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)
# Assign a port number
serverPort = 50997
serverSocket = socket(AF_INET, SOCK_STREAM)
#serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print ("hostname is: "), gethostname()
#print ("hostname is: "), socket.gethostname()
# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))
# Listen to at most 1 connection at a time
serverSocket.listen(1)
# Server should be up and running and listening to the incoming connections
while True:
print ("Ready to serve...")
# Set up a new connection from the client
connectionSocket, addr = serverSocket.accept()
try:
# Receives the request message from the client
message = connectionSocket.recv(1024)
print ("Message is: "), message
filename = message.split()[1]
print ("File name is: "), filename
f = open(filename[1:])
outputdata = f.read()
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.send("\r\n")
# Close the client connection socket
connectionSocket.close()
except IOError:
# Send HTTP response message for file not found
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n")
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
# Close the client connection socket
connectionSocket.close()
serverSocket.close()
The error I am exacly getting-
Ready to serve...
Message is:
File name is:
Traceback (most recent call last):
File "intro.py", line 56, in <module>
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
TypeError: a bytes-like object is required, not 'str'
You need to convert the string you are sending into bytes, using a text format. A good text format to use is UTF-8. You can implement this conversion like so:
bytes(string_to_convert, 'UTF-8')
or, in the context of your code:
connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8"))
connectionSocket.send(bytes("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n","UTF-8"))`

Socket Connection Refused [Errno 111]

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.

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.

Categories

Resources