(Using Python 3) I am trying to connect server and client and symply send a message from one to another but I don't know why I get this strange error: OSError: [WinError 10057]. Does anyone know why it happened? I did a bit of reaserch but didn't find anything, I think I made an error when making global variables, or is it somenthing with message encoding and decoding?
Here is my full error:
File "server_side.py", line 34, in
shell()
File "server_side.py", line 6, in shell
s.send(command.encode('utf-8'))
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a
sendto call) no address was supplied
Here is my server_side code:
import socket
def shell():
command = input('[+] Insert command: ')
s.send(command.encode('utf-8'))
message = target.recv(1024)
print(message.decode('utf-8'))
s = ''
target = ''
ip = ''
def server():
global s
global target
global ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(('192.168.1.109', 54321))#target ip, port more bit isti
s.listen(5)
print('[+] Listening for connections')
target, ip = s.accept()
print('[+] Connection established from: %s' %str(ip))
server()
shell()
And this is my client_side code:
import socket
def shell():
command = sock.recv(1024)
message = 'Hello there'
sock.send(message.encode('utf-8'))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.109', 54321)) #home ip
shell()
sock.close()
My command input on server_side example vould be the word : Hello, or somenthing like that.
You have to put the shell() function in a infinite loop, and you have to run the server_side code and then the client_side code.
Here is a bit changed code:
Server side code:
import socket
def shell():
command = input('[+] Insert command: ')
s.send(command.encode('utf-8'))
message = target.recv(1024)
print(message.decode('utf-8'))
s = ''
target = ''
ip = ''
def server():
global s
global target
global ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(('192.168.1.109', 54321))#target ip, port more bit isti
s.listen(5)
print('[+] Listening for connections')
target, ip = s.accept()
print('[+] Connection established from: %s' %str(ip))
while True:
server()
shell()
s.close()
Client side code:
import socket
def shell():
command = sock.recv(1024)
message = 'Hello there'
sock.send(message.encode('utf-8'))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.109', 54321)) #home ip
while True:
shell()
sock.close()
Related
So can someone please tell me how to have an admin-client shutting down the Server (server.py) in a socket multiple clients architecture? I want admin-client to type "shutdown" in client side then server will be shutdown. and right after submit, the server will call a function that shows network load graph . a graph with the number of requests per time slot.
Server:
`
import socket, threading
class ClientThread(threading.Thread):
def __init__(self,clientAddress,clientsocket):
threading.Thread.__init__(self)
self.csocket = clientsocket
print ("New connection added: ", clientAddress)
def run(self):
print ("Connection from : ", clientAddress)
#self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))
msg = ''
while True:
data = self.csocket.recv(2048)
msg = data.decode()
if msg=='bye':
break
print ("from client", msg)
self.csocket.send(bytes(msg,'UTF-8'))
print ("Client at ", clientAddress , " disconnected...")
LOCALHOST = "127.0.0.1"
PORT = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LOCALHOST, PORT))
print("Server started")
print("Waiting for client request..")
while True:
server.listen(1)
clientsock, clientAddress = server.accept()
newthread = ClientThread(clientAddress, clientsock)
newthread.start()
Client:
import socket
SERVER = "127.0.0.1"
PORT = 8080
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((SERVER, PORT))
client.sendall(bytes("This is from Client",'UTF-8'))
while True:
in_data = client.recv(1024)
print("From Server :" ,in_data.decode())
out_data = input()
client.sendall(bytes(out_data,'UTF-8'))
if out_data=='bye':
break
client.close()
`
I have tried
if message == "shutdown":
close()
exit(0)
but dont know how to apply it
In Python, I made a client.py and server.py with some simple socket code.
server.py:
import socket
HEADERSIZE = 10
PORT = 1235
ADDR = "192.168.198.1" # this is my local IP found from ipconfig in cmd
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ADDR, PORT))
s.listen(5)
while True:
client, address = s.accept()
print(f'Connection from {address} established')
msg = "Hello Client"
msg = f'{len(msg):<{HEADERSIZE}}'+msg
client.send(bytes(msg, "utf-8"))
client.py:
import socket
HEADERSIZE = 10
ADDR = "67.xxx.xxx.xx" # my public IP found from whatsmyip.com
PORT = 1235
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ADDR, PORT))
while True:
full = ''
new = True
while True:
msg = s.recv(16)
if new:
msglen = int(msg[:HEADERSIZE])
new = False
full += msg.decode("utf-8")
if len(full) - HEADERSIZE == msglen:
new = True
full = ''
print(full)
Previously, I had the addresses in both programs set to socket.gethostname() because I was working on my computer only. When I sent the client to my friend to test it out with the updated information you see here, I get this error code:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
The same thing happens when I run it on my computer.
I'm very new to sockets / networking, so I apologize if I'm missing something obvious, but I've been having issues with this and any help is appreciated
I'm struggling with getting reply back to client when pinging through socket server.
Trying to create something simple, where I can ping servers from client through socket server.
Client checks that socket server is online, socket server in "server" will respond status. Client sends the ping command to socket server, socket server initiate the ping to where ever. Raw printout will be sent to client.
What's the best way to do it?
First time working with sockets.
Server
#!/usr/bin/python3
import socket
import sys
HOST = '127.0.0.1'
PORT = 8085
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
# Bind socket
try:
s.bind((HOST, PORT))
except socket.error as msg:
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print('Socket bind complete')
#Start listening on socket
s.listen(10)
print('Socket now listening')
# Talk with client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print('Connected')
while True:
dataFromClient = conn.recv(1024)
print(dataFromClient.decode('utf-8'))
if not dataFromClient:
print("[Client] Disconnected")
break
conn.sendall(dataFromClient)
s.close()
Client
#!/usr/bin/python3
import socket
import subprocess
import os
SERVER = "127.0.0.1"
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((SERVER,8085))
os.system("clear")
os.system("cls")
while True:
data = input("Input: ")
clientSocket.send(data.encode())
# dataFromServer = clientSocket.recv(1024)
# print(dataFromServer.decode())
if data == "ping":
input1 = str(input("Enter command: "))
with subprocess.Popen(input1,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
for line in proc.stdout:
clientSocket.send(line)
print(proc.communicate())
elif data == "help":
print("Command: pingdl,destip=<isp>,repeat=<amount>")
clientSocket.close()
I've recently been tinkering around with the python socket module and I have come across an issue.
Here is my python server side script (im using python3.8.2)
import socket
#defin socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"connection from client has been established")
clientsocket.send(bytes("welcome to the server!", "utf-8"))
My server side script runs fine, however when i run the client script
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(127.0.0.1), 0))
msg = s.recv(1024)
print(msg.decode("utf-8"))
i get the following:
File "client.py", line 3
s.connect((socket.gethostname(127.0.0.1), 0))
^
SyntaxError: invalid syntax
I've tried changing the IP to my computer host name and gives the following:
raceback (most recent call last):
File "client.py", line 3, in <module>
s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))
NameError: name 'LAPTOP' is not defined
There are multiple issues:
when specifying IP addresses and hostnames, they must be formatted as strings (e.g. "127.0.0.1" and "LAPTOP-XXXXXXX"). Specifying them without quotes causes Python to attempt to interpret them as other tokens, such as variable names, reserved keyword, numbers, etc., which fails causing erros such as SyntaxError and NameError.
socket.gethostname() does not take an argument
specifying port 0 in the socket.bind() call results in a random high numbered port being assigned, so you either need to hardcode the port you use or dynamically specify the correct port in your client (e.g. by specifying it as an argument when executing the program)
in the server code, socket.gethostname() may not end up using the loopback address. One option here is using an empty string, which results in accepting connections on any IPv4 address.
Here's a working implementation:
server.py
import socket
HOST = ''
PORT = 45555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
host_addr = s.getsockname()
print("listening on {}:{}".format(host_addr[0], host_addr[1]))
s.listen(5)
while True:
client_socket, client_addr = s.accept()
print("connection from {}:{} established".format(client_addr[0], client_addr[1]))
client_socket.send(bytes("welcome to the server!", "utf-8"))
client.py
import socket
HOST = '127.0.0.1'
PORT = 45555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Output from the server:
$ python3 server.py
listening on 0.0.0.0:45555
connection from 127.0.0.1:51188 established
connection from 127.0.0.1:51244 established
Output from client:
$ python3 client.py
welcome to the server!
$ python3 client.py
welcome to the server!
Put the 127.0.0.1 as string in gethostname
In the /etc/hosts file content, You will have an IP address mapping with '127.0.1.1' to your hostname. This will cause the name resolution to get 127.0.1.1. Just comment this line. So Every one in your LAN can receive the data when they connect with your ip (192.168.1.*). Used threading to manage multiple Clients.
Here's the Server and Client Code:
Server Code:
import socket
import os
from threading import Thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.getfqdn() # it gets ip of lan
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = ("Hi Steven!!!" + timestamp).encode()
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
Client Code:
import socket
import os
import time
s = socket.socket()
host = '192.168.1.43' #my server ip
port = 10016
print(host)
print(port)
s.connect((host, port))
while True:
print((s.recv(1024)).decode())
s.close()
Output:
(base) paulsteven#smackcoders:~$ python server.py
Server is listening for connections...
Accepted connection from: ('192.168.1.43', 38716)
(base) paulsteven#smackcoders:~$ python client.py
192.168.1.43
10016
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
I have server and client side scripts for running a simple text transfer program, The server side works fine its just that when i connect with the client it show the error in the title.
Here is the client side code:
import socket
import select
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
IP = "127.0.0.1"
PORT = 33000
server.connect((IP, PORT))
while True:
sockets_list = [sys.stdin, server]
read_sockets, write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == server:
message = socks.recv(2048)
print(message)
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("ME: ")
sys.stdout.write(bytes(message, "ascii"))
sys.stdout.flush()
server.close()