So i've recently started testing out sockets and i have managed to create a server and client, which are both working together when i run them on the same pc. However, when i put in the server on a diffrent computer it gives me the following error: ""TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond""
Here is my server:
import socket
import pyautogui
import os
computerIP = socket.gethostbyname(socket.gethostname())
def Main():
host = computerIP
port = 5000
value = 0
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
while True:
data = conn.recv(1024).decode()
if not data:
break
elif data == "shift":
pyautogui.keyDown("shift")
elif data == "relshift":
pyautogui.keyUp("shift")
elif data == "logout":
os.popen("shutdown -l")
elif data == "click":
pyautogui.click()
pyautogui.click()
print ("from connected user: " + str(data))
data = str(data).upper()
print ("sending: " + str(data))
conn.send(data.encode())
conn.close()
if __name__ == '__main__':
Main()
My client:
import socket
def Main():
host = #same ip as server
port = 5000
mySocket = socket.socket()
mySocket.connect((host,port))
message = input(" -> ")
while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()
print ('Received from server: ' + data)
message = input(" -> ")
mySocket.close()
if __name__ == '__main__':
Main()
OS: Windows 8.1
Python verion: 3.4
I tried looking this up on the internet but since i'm pretty new to python i didn't understand much.
Tell me if there is anything i need to clearify.
Looks like the port is blocked due to some firewall.
Use socket.connect_ex() instead of socket.connect(). If the connection succeeds it would return 0, otherwise the value of the errno variable will help you debug why the connection failed.
Prior to the connection also use socket.settimeout() so that the connection times out in the given no. of seconds.
Related
I am writing a simple socket app, and I have met this message and don't know how to fix it.
server_input =s.recv(1024)
ConnectionResetError: [Errno 54] Connection reset by peer
server.py
import socket
def main():
s = socket.socket()
port = 58257
client_address = "localhost"
s.bind((client_address, port))
s.listen(2)
user_input = input("Enter a message: ")
s.send(user_input.encode())
s.close()
if __name__ == '__main__':
main()
client.py
import socket
def main():
s = socket.socket()
#host = socket.gethostname()
port = 58257
client_address = "localhost"
s.connect((client_address, port))
print("connet ")
server_input =s.recv(1024)
server_input.decode()
print("Received message: " + server_input)
s.close()
if __name__ == '__main__':
main()
It is there any problem with my code? Thank you so much!!!
s.bind((client_address, port))
s.listen(2)
user_input = input("Enter a message: ")
s.send(user_input.encode())
The server needs to call accept on the server socket to get a socket for the connected client, then call send on this connected socket, not on the server socket.
Without this the connect in the client will still succeed, since it is done by the OS kernel on the server side. But since the connected socket is never accepted by the server it will be reset, thus resulting in the error you see.
So a more correct code on the server side would be
...
s.listen(2)
c,_ = s.accept()
user_input = input("Enter a message: ")
c.send(user_input.encode())
c.close()
Note that your client code has also other problems, i.e it should be
print("Received message: " + server_input.decode())
I've been trying to make a program that would allow me to remote into my computer. It works perfectly when both computers are connected to the same network, and I am able to access a sort of command line that I have coded.
I am very inexperienced with networks and I'm not entirely sure what sort of information is needed.
This is the code I used:
Server:
import sys
import socket
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
print("SocketCreationError: " +str(msg))
def bind_socket():
try:
global host
global port
global s
print("binding the port " + str(port)+"...")
s.bind((host,port))
s.listen(5)
except socket.error as msg:
print("SocketBindingError: " + str(msg))
print("retrying...")
bind_socket()
def socket_accept():
conn,address = s.accept()
print("Connection established. \nIP:"+address[0]+"\nPort:"+str(address[1]))
print(str(conn.recv(1024), "utf-8"), end="")
send_command(conn)
conn.close()
#allows user to send command to client computer
def send_command(conn):
while True:
try:
cmd = input(">")
if cmd == 'exit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
clientResponse = str(conn.recv(1024),"utf-8")
print(clientResponse, end="")
except Exception:
print("Something went wrong...")
def main():
create_socket()
bind_socket()
socket_accept()
main()
Client:
import socket
import os
import subprocess
#connect to socket and send cwd
s = socket.socket()
host = 'myIP'
port = 9999
s.connect((host, port))
s.send(str.encode(os.getcwd()))
#allows form of command line on host pc
while True:
try:
data = s.recv(1024)
outputStr = ""
if data.decode("utf-8") == 'dir':
dirList = os.listdir(os.getcwd())
for i in dirList:
print(i)
outputStr = outputStr + i + "\n"
elif data[:2].decode("utf-8") == 'cd':
dirTo = data[3:].decode("utf-8")
print(data[3:].decode("utf-8"))
os.chdir(os.getcwd() + "\\" + dirTo)
elif len(data) > 0:
cmd = subprocess.Popen(data.decode("utf-8"), shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr=subprocess.PIPE)
outputByte = cmd.stdout.read() + cmd.stderr.read()
outputStr = str(outputByte, "utf-8")
print(outputStr)
cwd = os.getcwd()
s.send(str.encode(outputStr +"\n"+cwd))
#handle something going wrong and just allows to continue
except Exception:
cwd = os.getcwd()
s.send(str.encode("Something went wrong...\n"+ cwd))
I am using ipv4 addresses. I think it may have something to do with port forwarding on the server side, but again I am not sure?
Thank you for any answers in advance :)
You can't connect to your computer using a remote network because of port forwarding. If you dont know what that is, I recommend taking a look at the Wikipedia article on it: https://en.wikipedia.org/wiki/Port_forwarding
There are many different methods to perform Port Forwarding, the simplest of which is the UPnP/IGD (look it up), but if you're just interested in being able to Access your computer remotely, you could just use an SSH (Secure Shell Connection) to do just this (I think it Works on remote networks as well). If you're using Linux this should be pretty easy to set up, just look up how to do it. Good luck!
I'm creating a client to server based chat client and every time I setup a server and a client, the server keeps listening for a connection and when the client attempts to connect this error appears [WinError 10054] An existing connection was forcibly closed by the remote host, however the server still listens for a connection. I'm using python version 3.6.1
Script
import socket
import threading
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mode = input("Enter 1 for server mode and enter 2 for client mode")
if mode == "1":
def get_ip():
try:
stest = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
stest.connect(('10.255.255.255', 1))
IP = stest.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
stest.close()
return IP
print("IP: " + get_ip())
s.bind((get_ip(), 7999))
s.setblocking(0)
print("Waiting for connection")
while True:
try:
data, addr = s.recvfrom(1024)
if data.decode() == "Quit":
quitmsg = str(addr) + " has quit the chat."
clients.remove(addr)
for client in clients:
s.sendto(quitmsg.encode("utf-8"), client)
break
elif data:
print(data)
if addr not in clients:
clients.append(addr)
print(clients[0])
for client in clients:
print(client)
s.sendto(data, client)
except:
pass
s.close()
elif mode == "2":
while True:
try:
ip = input("Enter in an ip address")
socket.inet_aton(ip)
except socket.error:
print("Invalid IPv4 address")
continue
while True:
try:
port = int(input("Enter in port number"))
except ValueError:
print("Invalid Port Number")
continue
break
addr = (ip, port)
break
s.connect(addr)
def recvmsg():
while True:
data = s.recv(1024)
print(data)
if data:
print(data.decode())
recv = threading.Thread(name="recvmsg", target=recvmsg)
recv.daemon = True
recv.start()
while True:
string = input(">>")
s.send(string.encode("utf-8"))
if str(string) == "Quit":
break
s.close()
print("Disconnected from chat")
Server Waiting For connection even after client can't connect
Client Failed to connect
If your server is not on the local network, make sure port 7999 is open and forwarded on its access point. Otherwise the packets will just be dropped by the router. If it is on your local network, still try forwarding. Also according to https://www.speedguide.net/port.php?port=7999 the port has been used by a worm, so maybe permanently closed on the other network?? Unlikely but possible.
I am trying to build a TCP Chat Program that is multithreaded. So far I think most of the functions are setup fine. When starting the server and connecting with a client only responses sent from the server are broadcasted to all clients connected. I think I figured out why that is and it comes from the CONNECTION_LIST array I have. The server appends all clients to this list and I thought I had the same thing going for the clients but the client instance never sees this list so when sending messages they messages aren't sent anywhere. I basically need a way to copy the CONNECTION_list from the server instance over to the connected clients. I been trying figure out how to possibly do this all day and its driving me crazy.
import socket
import platform
import threading
import sys
import time
import os
'''Define Globals'''
HOST = ""
PORT = 25000
ADDR = (HOST, PORT)
CONNECTION_LIST = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
'''Connect Client to the Server'''
def client_connect():
server_ip = input("[+] Server's IP to connect to: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((server_ip, PORT))
print("[+] Connected to Server at address: %s" %client.getpeername()[0])
except ConnectionRefusedError:
print("[*] No Server Listening at Specified Address")
sys.exit()
communicate(client)
'''Threaded loop to continue listening for new connections'''
def server_loop():
server.bind(ADDR)
server.listen(10)
print("[*] Server started on %s" %platform.node())
while True:
client_socket, client_addr = server.accept()
CONNECTION_LIST.append(client_socket)
print("\r[+] New Connection from: %s" %client_addr[0])
'''Broadcast data to all clients except sender'''
def broadcast_data(sock, message):
for socket in CONNECTION_LIST:
if socket != server and socket != sock:
try:
socket.send(str.encode("[%s] => %s" %(os.getlogin(),message)))
except:
socket.close()
CONNECTION_LIST.remove(socket)
'''Server Host Connect Back'''
def self_connect():
sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sc.connect(("localhost", 25000))
CONNECTION_LIST.append(sc)
communicate(sc)
def communicate(client):
dump_thread = threading.Thread(target=dump, args=(client,))
dump_thread.start()
while True:
try:
time.sleep(0.5)
data = input("> ")
broadcast_data(client, data)
except:
print("[*] Error - Program Terminating")
client.close()
sys.exit()
def dump(client):
while True:
print(client.recv(1024).decode("utf-8"))
def main():
server_thread = threading.Thread(target=server_loop)
while True:
try:
print("Select Operating Mode")
print("---------------------")
print("1. Server Mode")
print("2. Client Mode")
mode = int(input("Enter mode of operation: "))
print("\n\n")
if mode in [1,2]:
break
else:
raise ValueError
except ValueError:
print("Enter either (1) for Server or (2) for Client")
if mode == 1:
server_thread.start()
time.sleep(1)
self_connect()
elif mode == 2:
client_connect()
main()
This is probably very simple, but I am having trouble with it.
This is code I am using for the server.
I've searched for this but I only found different kinds of sockets to the one I am using.
server = socket.socket()
server.bind(("localhost", 6969))
server.listen(1)
socket_client, datos_client = server.accept()
print ("Wainting message...")
data = socket_client.recv(1000)
print ("Message:", data)
send1 = bytes("Bye","utf-8")
socket_client.send(send1)
print ("Closing..." )
socket_client.close()
server.close()
And this is the code for the client:
import socket
def main():
my_socket_client = socket.socket()
my_socket_client.connect(("localhost", 6969))
bufsize = 1000
print("Send message")
message=input()
data2 = bytes(mensaje,"utf-8")
#enviar los datos
my_socket_client.send(data2)
data_received= my_socket_client.recv(bufsize)
print (data_received)
I am not sure what your problem is since you didn't ask a question so i will just show you a client + basic command server that i have built in the same way you built yours you said "I only found different kinds of sockets to the one I am using." so i hope this is what you are looking for
Here is an example of a simple command server:
if you run the server code and then run the client you will be able to type in the client and send to the server. if you type TIME you will get from the server a respons which contains a string that has the date of today and the other commands work in the same way. if you type EXIT it will close the connection and will send from the server the string closing to the client
server:
import socket
import random
from datetime import date
server_socket = socket.socket() # new socket object
server_socket.bind(('0.0.0.0', 8820)) # empty bind (will connect to a real ip later)
server_socket.listen(1) # see if any client is trying to connect
(client_socket, client_address) = server_socket.accept() # accept the connection
while True: # main server loop
client_cmd = client_socket.recv(1024) # recive user input from client
# check waht command was entered
if client_cmd == "TIME":
client_socket.send(str(date.today())) # send the date
elif client_cmd == "NAME":
client_socket.send("best server ever") # send this text
elif client_cmd == "RAND":
client_socket.send(str(random.randrange(1,11,1))) # send this randomly generated number
elif client_cmd == "EXIT":
client_socket.send("closing")
client_socket.close() # close the connection with the client
server_socket.close() # close the server
break
else :
client_socket.send("there was an error in the commend sent")
client_socket.close() # just in case try to close again
server_socket.close() # just in case try to close again
client:
import socket
client_socket = socket.socket() # new socket object
client_socket.connect(('127.0.0.1', 8820)) # connect to the server on port 8820, the ip '127.0.0.1' is special because it will always refer to your own computer
while True:
try:
print "please enter a commend"
print "TIME - request the current time"
print "NAME - request the name of the server"
print "RAND - request a random number"
print "EXIT - request to disconnect the sockets"
cmd = raw_input("please enter your name") # user input
client_socket.send(cmd) # send the string to the server
data = client_socket.recv(1024) # recive server output
print "the server sent: " + data # print that data from the server
print
if data == "closing":
break
except:
print "closing server"
break
client_socket.close() # close the connection with the server
you have a typo .
edit this line in client from
data2 = bytes(mensaje,"utf-8")
to
data2 = bytes(message,"utf-8")
I tried your code, and made a couple of changes:
Server side:
import socket
server = socket.socket()
server.bind(("localhost", 6969))
server.listen(1)
socket_client, datos_client = server.accept()
print ("Waiting message...")
data = socket_client.recv(1000)
print ("Message:", data )
# Same change made as with client side
send1 = bytes("Bye") #,"utf-8")
socket_client.send(send1)
print ("Closing..." )
socket_client.close()
server.close()
Client side:
import socket
my_socket_client = socket.socket()
my_socket_client.connect(("localhost", 6969))
bufsize = 1000
print("Send message")
# I changed it to raw_input(); input() does not for string input with python 2.7
message=raw_input()
# Are you trying to encode the message? To make it simple, skip it
data2 = bytes(message) # ,"utf-8")
#enviar los datos
my_socket_client.send(data2)
data_received= my_socket_client.recv(bufsize)
print (data_received)
Sample output from server side:
Waiting message...
('Message:', 'message from client')
Closing...
Sample output from client side:
Send message
message from client
Bye