Here is the senario:
Server listens to two ports 9999, 9998 via the host 10.10.10.1
Port 9999 for clients & Port 9998 for the controller
I was able to connect client and the controller to the server and control the client from the controller without ssl socket.
I wanted to use encrypted socket I added ssl certificate socket connection, The client does not connect to the server via SSL_SOCK as the controller too.
I appreciate your help or suggetion.
server :
s=socket(AF_INET, SOCK_STREAM)
s.bind(("10.10.10.1",9999))
s.listen(5)
port = 9999
password = "password"
bridgeport = 9998
allConnections = []
allAddresses = []
def getConnections():
for item in allConnections:
item.close()
del allConnections[:]
del allAddresses[:]
while 1:
try:
q,addr=s.accept()
connstream = ssl.wrap_socket(q, server_side=True, certfile="server.crt", keyfile="server.key", ssl_version=ssl.PROTOCOL_SSLv23)
connstream.setblocking(1)
allConnections.append(connstream)
allAddresses.append(addr)
except:
print "YOU ARE NOT CONNECTED!! TRY AGAIN LATER"
time.sleep(10.0)
break
def main():
bridge=socket(AF_INET, SOCK_STREAM)
bridge.bind(("10.10.10.1",9998))
bridge.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
while 1:
bridge.listen(1)
q,addr=bridge.accept()
bridgestream = ssl.wrap_socket(q, server_side=True, certfile="server.crt", keyfile="server.key", ssl_version=ssl.PROTOCOL_SSLv23)
cpass = bridgestream.recv(4096)
if (cpass == password):
print "Controller is connected"
else:
print "Controller not conected"
try:
main()
except:
try:
del allConnections[:]
del allAddresses[:]
except:
pass
Controller :
host = '10.10.10.1'
port = 9998
password = "password"
def main():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s, ca_certs="server.crt", cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect((host, port))
except:
sys.exit("[ERROR] Can't connect to server")
ssl_sock.sendall(password)
Client:
host = "10.10.10.1"
port = 9999
def main(host, port):
while 1:
connected = False
while 1:
while (connected == False):
try:
print host
print port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print s
ssl_sock = ssl.wrap_socket(s, ca_certs="server.crt", cert_reqs=ssl.CERT_REQUIRED)
print "ssl_sock"
ssl_sock.connect((host,port))
print "Connected"
connected = True
except:
print "The client not Connected yet"
time.sleep(5)
while 1:
try:
main(host, port)
except:
time.sleep(5)
I had a similar issue and would suggest two approaches:
Try raw TCP socket first (without ssl.wrap_socket()). If this works, use a tool such as netstat to diagnose what ports and IP addresses are used, in case something is blocking either.
Try creating an SSLContext on either side with something like this:
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
ssl_context.verify_mode = ssl.CERT_NONE
stream_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_socket = ssl_context.wrap_socket(stream_socket, server_hostname=hostname)
_socket.connect((hostname, port))
In other words, don't enforce certificate usage first and try specifying protocol. Hope this helps!
Related
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.
I am getting the above error..My server and client can send and receive their first messages but I get this error if I try to send more than one message.
My Server Code is here
import socket
import threading
import time
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5354
maxconnections = 9
ip = socket.gethostbyname(socket.gethostname())
print(ip)
server = (ip, port)
FORMAT = 'utf-8'
listensocket.bind((server))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
msg = f'\[ALERT\] {address} has joined the chat.'
lstbox.insert(0, msg)
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Client: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5986
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
And my client code is same with minor difference
import socket
import time
import threading
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5986
maxconnections = 9
ip = socket.gethostname()
print(ip)
FORMAT = 'utf-8'
host = 'MY_IP' # My actual ip is there in the code
listensocket.bind((host, port))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Server: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5354
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
Please let me know what changes are required to be made in order to make it run for every message.
I tried to put
g.connect((hostname, port))
the above line in the loop so that it will connect every time loop iterates. But it did not help.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
...
if at==0:
g.connect((hostname, port))
...
g.send(msg.encode())
at += 1
else:
...
g.send(msg.encode())
In the if at==0 condition it connects to the server, in the else part not. But is still trying to send something on the not connected socket.
this is a server code that i am running on remote server.
serv.py
import time, socket, sys
print('Setup Server...')
time.sleep(1)
#Get the hostname, IP Address from socket and set Port
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_name = socket.gethostname()
ip = socket.gethostbyname(host_name)
port = 1234
soc.bind((host_name, port))
print(host_name, '({})'.format(ip))
name = input('Enter name: ')
soc.listen(1) #Try to locate using socket
print('Waiting for incoming connections...')
connection, addr = soc.accept()
print("Received connection from ", addr[0], "(", addr[1], ")\n")
print('Connection Established. Connected From: {}, ({})'.format(addr[0], addr[0]))
#get a connection from client side
client_name = connection.recv(1024)
client_name = client_name.decode()
print(client_name + ' has connected.')
print('Press [bye] to leave the chat room')
connection.send(name.encode())
while True:
message = input('Me > ')
if message == 'bye':
message = 'Good Night...'
connection.send(message.encode())
print("\n")
break
connection.send(message.encode())
message = connection.recv(1024)
message = message.decode()
print(client_name, '>', message)
This is client code that i am running on local system.
clie.py
import time, socket, sys
print('Client Server...')
time.sleep(1)
#Get the hostname, IP Address from socket and set Port
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
#get information to connect with the server
print(shost, '({})'.format(ip))
server_host = input('Enter server\'s IP address:')
name = input('Enter Client\'s name: ')
port = 1234
print('Trying to connect to the server: {}, ({})'.format(server_host, port))
time.sleep(1)
soc.connect((server_host, port))
print("Connected...\n")
soc.send(name.encode())
server_name = soc.recv(1024)
server_name = server_name.decode()
print('{} has joined...'.format(server_name))
print('Enter [bye] to exit.')
while True:
message = soc.recv(1024)
message = message.decode()
print(server_name, ">", message)
message = input(str("Me > "))
if message == "bye":
message = "Leaving the Chat room"
soc.send(message.encode())
print("\n")
break
soc.send(message.encode())
Now if the host server is different the connection is not established. but if the host is same then it's working properly and sending texts properly. i want run this code in different server how to do please help me anyone.
In the server script, you use :
host_name = socket.gethostname()
This will probably give you "127.0.0.1".
What you need is for the server to listen to "0.0.0.0" to accept connections from everywhere.
So this will probably do :
host_name = "0.0.0.0"
I have a server and I need it to receive multiple connections and messages.
The server receives new connections without problems but it doesn't get multiple messages from one connection.
import socket
import select
HEADER_LENGTH = 1024
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
server_socket.bind((HOST, PORT))
except socket.error as e:
print(str(e))
print("Server is connected")
server_socket.listen(5)
sockets_list = [server_socket]
clients = {}
print("Server is listening")
def receive_message(conn):
try:
data = conn.recv(HEADER_LENGTH)
if not len(data):
return False
strdata = data.decode('utf-8')
print(strdata)
return strdata
except Exception as e:
print(e)
return False
def handle_client():
conn, addr = server_socket.accept()
print(f"Accepted new connection from {addr[0]}:{addr[1]}")
sockets_list.append(conn)
while True:
read_sockets, _, exception_sockets = select.select(sockets_list, [], [], 0)
for i in read_sockets:
if i == server_socket:
handle_client()
else:
print("received message")
message = receive_message(i)
if message is False:
sockets_list.remove(i)
try:
del clients[i]
except KeyError:
pass
continue
if message is not None:
clients[i] = message
if message is not None:
for client_socket in clients:
if client_socket != i:
client_socket.send(str.encode(message))
print("sent to all players")
What happens it that after receiving the first message, the server stops receiving messages from that connection.
And of course there is a lot more code but I showed you the relevant code.
I'll be very happy if someone helps me with that, I've surfed the web so much but haven't seen a solution for my problem.
updates:
I've tried to put socket.close() on my client side(written in Java) and then server gets maximum 2 messages and the problems with it are:
1. The server gets maximum 2 messages.
2. the connection changes(I need that the connection will stay static if possible)
try this code block
#-*- coding:utf-8 -*-
import socket
import sys
#get machine ip address
server_ip = socket.gethostbyname(socket.gethostname())
#create socket object
s = socket.socket()
#define port number
port = 6666
#bind ip and port to server
s.bind((server_ip,port))
#now waiting for clinet to connect
s.listen(5)
print("Enter this ip to connect your clinet")
print(server_ip)
clients = []
flag = True
recv_data = ""
if not clients:
c, addr = s.accept()
print("this is c ",c," this is Addr ",addr)
clients.append(c)
recv_data = c.recv(1024)
print(recv_data.decode("utf-8"))
if flag == True:
while recv_data.decode("utf-8") != "EX":
recv_data = c.recv(1024)
recv_data.decode("utf-8")
if recv_data.decode("utf-8") == "EX":
s.close()
print("check false")
break
s.close()
I have a python script that receives tcp data from client and I want to send a response to a specific client (I handle more than 500). This command comes from a mysql database and I handle the clientsocket by a dictionary, but the script is down when it receives a lot of connections.
How can I store the clientsocket in mysql database, or which is the best way to handle the clientsocket?
My code is:
import thread
from socket import *
def sendCommand():
try:
for clientsocket,id_client in conn_dict.iteritems():
if id_cliente == "TEST_from_mysql_db":
clientsocket.send("ACK SEND")
break
except:
print "NO"
def handler(clientsocket, clientaddr):
print "Accepted connection from: ", clientaddr
while 1:
data = clientsocket.recv(buf)
if not data:
break
else:
conn_dict[clientsocket] = id_client
sendCommand()
clientsocket.close()
if __name__ == "__main__":
conn_dict = dict()
host = str("XXX.XXX.XXX.XXX")
port = XXX
buf = 1024
addr = (host, port)
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversocket.bind(addr)
serversocket.listen(2)
while 1:
print "Server is listening for connections\n"
clientsocket, clientaddr = serversocket.accept()
thread.start_new_thread(handler, (clientsocket, clientaddr))
serversocket.close()
I am using sockets for a client / server application, where I need to send a variable from the server back to the client when the use clicks a button, for example. I am using wxpython.
Here is a sample of my server code:
def handler(self, clientsocket, clientaddr):
data22 = clientsocket.recv(1024)
while 1:
msg = "Message to send"
clientsocket.sendall(msg)
clientsocket.close()
def listen(self):
host = ''
port = 55567
buf = 1024
addr = (host, port)
self.serversocket = socket(AF_INET, SOCK_STREAM)
self.serversocket.bind(addr)
self.serversocket.listen(2)
while 1:
if self.canExit:
print "trying to break"
break
print "Server is listening for connections\n"
clientsocket, clientaddr = self.serversocket.accept()
threading.Thread(target=self.handler, args=(clientsocket, clientaddr)).start()
print "closing the socket"
self.serversocket.close()
And here is a sample of my client code:
def SendFolder(self):
HOST = host=self.params["databaseLocation"] # The remote host
port = 55567
buf = 1024
addr = (host, port)
clientsocket = socket(AF_INET, SOCK_STREAM)
clientsocket.connect(addr)
if self.abortThisJob != False:
clientsocket.sendall(self.abortThisJob)
else:
clientsocket.sendall("Send Job")
self.listenThread = threading.Thread(target=self.listen, args=(clientsocket, buf))
self.listenThread.daemon= True
self.listenThread.start()
def listen(self, clientsocket, buf):
while 1:
data = raw_input(">> ")
clientsocket.send(data)
data = clientsocket.recv(buf)
print data