How to use a variable as the socket server ip address - python

So I would like to have a variable as the socket server ip address... I have some issues. I get the issue with server.bind(ADDR)
import socket
import requests
import threading
def controller(conn, addr):
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNET:
connected = False
print(f'{msg}')
def start():
print('Server: Server Started')
server.listen()
while True:
conn, addr = server.accept()
thread = threading.Thread(target = controller, args = (conn, adrr))
thread.start()
host_name = socket.gethostname()
prip = socket.gethostbyname(host_name)
puip = requests.get('https://api.ipify.org').text
HEADER = 128
PORT = 5050
SERVER = puip
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNET = '!DISCONNECT'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
start()
Error Message:
server.bind((SERVER, PORT))
OSError: [WinError 10049] The requested address is not valid in its context

Related

Python Client / Server with Multiprocessing

I cant figure out why the client is not communicating with the Server (2 seperate jupyter notebooks with own kernel), no error messages - any suggestions?
the following code is working (without multiprocessing):
Server:
import socket
HOST = '127.0.0.1'
PORT = 50000
def start_server():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
print ('waiting for client')
conn, addr = s.accept()
print('client connected #', addr[0], 'port:', addr[1])
return conn
Server0 = start_server()
Client:
import socket
HOST = '127.0.0.1'
PORT = 50000
data = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect_ex((HOST, PORT))
while True:
byte_message = s.recv(1024)
string_message = byte_message.decode('utf8')
header, time, data = string_message.split(' ')
if header == 'close':
s.shutdown(socket.SHUT_RDWR)
s.close()
print('client connection shut down')
header = ''
elif header == '<<':
print(time,float(data))
else:
pass
As soon as I pack the client into a function and run it as a process, client and server do not connect anymore(no error is given, and the server doesent get to this line:
print('client connected #', addr[0], 'port:', addr[1])
not working client:
import socket
import multiprocessing
HOST = '127.0.0.1'
PORT = 50000
def client():
data = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect_ex((HOST, PORT))
while True:
byte_message = s.recv(1024)
string_message = byte_message.decode('utf8')
header, time, data = string_message.split(' ')
if header == 'close':
s.shutdown(socket.SHUT_RDWR)
s.close()
print('client connection shut down')
header = ''
elif header == '<<':
print(time,float(data))
else:
pass
client_process = multiprocessing.Process(target= client)
client_process.start()

Python Sockets: Socket not closing when connected = False

When the disconnect message is received from my client(A django site sending the data), my socket isn't closing and this is preventing the rest of the code in my python file from running. If anybody knows what is causing this, help would be great.
My Code:
import threading
import queue
import socket
HEADER = 64
PORT = 6060
SERVER = '0.0.0.0'
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT!"
my_queue = queue.Queue()
print(SERVER)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
else:
my_queue.put(msg)
print(f"[{ADDR}] {msg}")
conn.send("MSG Received".encode(FORMAT))
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server Is Listening On {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[Starting] Server")
start()
msg = my_queue.get()
print(msg)

Why does the Python Socket program stop working when converted to an exe file?

I have written an online chess app, using Python and Sockets. When I run the server and connect the clients, everything runs perfectly smooth. However, when I convert the client into an exe file and run it, the client isn't able to connect to the server anymore.
I have also tried to convert the server into an executable and it stopped working either. I think it has problems with the command server.listen(), because the ouput is only [STARTING] Server is starting... (More details in the server side code below)
Has anybody encountered problems too, when converting a socket app into an exe file? I didn't get any results with a Google search.
Shortened client side code:
import socket
HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
NONE_MESSAGE = "!NONE"
OPPONENT_DISCONNECTED = "!OPPONENT_DISCONNECTED"
SERVER = "192.168.56.1"
ADDR = (SERVER, PORT)
def send(client, msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
def recieve(client):
send(client, NONE_MESSAGE)
msg_length = client.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = client.recv(msg_length).decode(FORMAT)
if msg != NONE_MESSAGE:
return msg
return False
Server side code:
import socket
import threading
import random
HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
NONE_MESSAGE = "!NONE"
OPPONENT_DISCONNECTED = "!OPPONENT_DISCONNECTED"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def recieve(conn):
send(conn, NONE_MESSAGE)
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg != NONE_MESSAGE:
return msg
return False
def send(conn, msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
conn.send(send_length)
conn.send(message)
def get_opponent(addr):
for c1, c2 in client_pairs:
if c1 == addr:
return c2
if c2 == addr:
return c1
return None
def handle_client(conn, addr):
global new_client
global new_client_name
name = recieve(conn)
if new_client:
print(f"[NEW CONNECTION] {addr} connected to {new_client}")
client_pairs.append((new_client, addr))
color = random.choice(['w', 'b'])
send(conn, color+new_client_name)
if color == 'w':
messages_to_send[new_client] = 'b'+name
else:
messages_to_send[new_client] = 'w'+name
new_client = None
new_client_name = None
else:
new_client_name = name
new_client = addr
print(f"[NEW CONNECTION] {addr} waiting")
connected = True
while connected:
if addr in messages_to_send.keys():
send(conn, messages_to_send[addr])
del messages_to_send[addr]
if addr in disconnects:
send(conn, OPPONENT_DISCONNECTED)
disconnects.remove(addr)
msg = recieve(conn)
if msg:
if msg == DISCONNECT_MESSAGE:
if new_client == addr:
new_client = None
opponent = get_opponent(addr)
if opponent:
disconnects.append(opponent)
connected = False
opponent = get_opponent(addr)
if opponent:
messages_to_send[opponent] = msg
print(f"[{addr}] {msg}")
conn.close()
new_client = None
new_client_name = None
messages_to_send = {}
client_pairs = []
disconnects = []
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount()-1}")
print("[STARTING] Server is starting...")
start()

how can i send images from the client to the server (Socket python)

Clients
import socket
HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = "192.168.1.105"
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
print(client.recv(2048).decode(FORMAT))
send(DISCONNECT_MESSAGE)
Server
import socket
import threading
HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
print(f"[{addr}] {msg}")
conn.send("Msg received".encode(FORMAT))
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
** So my idea is that I want to put the client file on my second computer and this client will take a screenshot
On each mouse click and then sends this img to the server and removes it from the second computer **
If anyone has a solution, please help me, and thank you.
notice : this for local connection

Using proxy and multiple sockets in python

I'm writing a proxy with tcp connection that listens to multiple ports from a client and forward it to a server.
The problem is that the software hangs on the sock.accept.
Maybe I'm doing a messy logic here, but I need a client that connects to a PC, and that PC connects to another device. So I wrote that small proxy, and I get INVALID ARGUMENT ERROR in socket.accept()
import select
import socket
import threading
class Proxy(object):
def __init__(self, ip, ports):
self._ip = ip
self._sockets = []
self._proxy = {}
for port in ports:
self._proxy[port] = self.add_socket(port)
def add_socket(self, port=None):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if port:
# sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind(('0.0.0.0',port))
self._sockets.append(sock)
return sock
def get_client(self, src_sock, src_addr):
src_ip, src_port = src_addr
_, dst_port = src_sock.getsockname()
if src_ip == self._ip:
# got packet from device
dst_addr = ("10.8.8.210", dst_port)
else:
# got packet from client
dst_addr = self._ip, dst_port
print(">", src_port, dst_addr)
dst_sock = self._proxy[src_port]
return dst_sock, dst_addr
def run(self):
while True:
read_list, _, _ = select.select(self._sockets, [], [])
if read_list:
for sock in read_list:
try:
conn, addr = sock.accept()
data = conn.recvfrom(16*2024)
# print("got data from {} {}".format(sock, addr))
dst_sock, dst_addr = self.get_client(sock, addr)
# print("forwarding data from {} to {}".format(addr, dst_addr, len(data)))
dst_sock.sendto(data, dst_addr)
except:
raise # pass # print("no recipient for data")
for s in self._sockets:
s.close()
ports = [30001,30002,30003, 30070, 30071,30072,30075]
p = Proxy("192.168.2.10", ports)
p.run()
You have to call listen on the socket before accept:
adding sock.listen(1) to add_socket after bind
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', port))
sock.listen(1)
self._sockets.append(sock)
then allows you to call accept without the error. You may want to set the listen backlog to a greater number.

Categories

Resources