i can recv info from client but i dont know how to recv it from server.
"i think in line 15 i need to change "socket" to somethong"
it must be that type: 'socket.socket'
client:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET = IP, SOCK_STREAM = TCP
client.connect(('127.0.0.1', 1002)) # 127.0.0.1
while True:
command = input('>>>')
if command == 'stop':
exit()
command = command.encode('utf-8')
client.send(command)
get = socket.recv(2048)
get = get.decode('utf-8')
print('recieve',get)
server:
import socket
import subprocess
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET = IP, SOCK_STREAM = TCP
server.bind(('127.0.0.1', 1002)) # 127.0.0.1
server.listen()
client_socket, client_address = server.accept()
print(type(client_socket))
while True:
get = client_socket.recv(2048)
get = get.decode('utf-8')
print('recieve',get)
output = subprocess.check_output(get, shell=True)
client_socket.send(output)
output from client:
File "C:\Users\rusla\Desktop\client.py", line 15, in <module>
get = socket.recv(1024)
AttributeError: module 'socket' has no attribute 'recv'
Related
(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()
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 am new in working with python and working on API of XenServer
I am trying to start a script which uses the XenServer API to start a virtual machine upon receiving the data from the client. The code is below
import socket
import json
import startvm
ip = socket.gethostbyname(socket.gethostname())
print("ip of server machiene = " + ip )
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9999
# bind to the port
serversocket.bind((host, port))
print ("server is waiting for data")
# queue up to 5 requests
serversocket.listen(5)
running = True
while True:
# establish a connection
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
while running:
receivedData = clientsocket.recv(1024)
#json = receivedData
if receivedData:
print (receivedData)
execfile(startvm.py)
else:
print (" -- data end --" )
running = False
serversocket.close()
I am using execute(script name). and it gives me the following error
on the server side script
ip of server machine = 192.168.0.11
server is waiting for data
Traceback (most recent call last):
Got a connection from ('127.0.0.1', 50128)
File "/Users/jasmeet/IdeaProjects/vKey-cloud/server.py", line 45, in
<module>
0
execfile(startvm.py)
AttributeError: 'module' object has no attribute 'py'
and this on client script
connecting to server at 127.0.0.1 on port 9999
Traceback (most recent call last):
File "/Users/jasmeet/IdeaProjects/vKey-cloud/client.py", line 27, in
<module>
clientSocket.send(str(x))
socket.error: [Errno 32] Broken pipe
can anybody explain me how to do it exactly thank you in advance
you could import the file at the beginning like:
from startvm.py import A_FUNCTION_FROM_THAT_FILE
so that it's optimized
and replace
execfile(startvm.py)
with
A_FUNCTION_FROM_THAT_FILE(*args)
ex:
# script A.py
from B.py import customfunc
customfunc(2, 4)
# script B.py
def customfunc(x, y):
return x*y
writing the following code for server.py solved my problem
# server.py
import socket
import json
import startvm
ip = socket.gethostbyname(socket.gethostname())
print("ip of server machiene = " + ip )
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
#host = socket.gethostname()
#port = 9999 # port 80
host = "127.0.0.1"
port = 9999
# bind to the port
serversocket.bind((host, port))
print ("server is waiting for data")
# queue up to 5 requests
serversocket.listen(5)
while True:
running = True
# establish a connection
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
while running:
receivedData = clientsocket.recv(1024)
#json = receivedData
if receivedData:
print (receivedData)
#execfile('startvm.py')
else:
print (" -- data end --" )
running = False
I like to have one port that first use for connect to another server and after that this port use to be a server and another clients connect to it.
I used python socket for client now I want to use it for server socket.
my code :
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12349
portt = 12341 # Reserve a port for your service.
s.bind((host, portt)) # Bind to the port
s.connect((host, port))
s.listen(5) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
print c
print 'Got connection from', addr
print s.recv(1024)
s.close
and the output is
Traceback (most recent call last):
File "client.py", line 12, in <module>
s.listen(5) # Now wait for client connection.
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument
How can I do that.
thank you for your answers!
Not sure what you are trying to do here. Seems to me that you are mixing client and server code in the same app.
For reference, you can create a simple echo server like this:
import socket
HOST = ''
PORT = 12349
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
And a simple echo client like this:
import socket
HOST = 'localhost'
PORT = 12349
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
I get the following error when I want to run this code. I made a mistake I do not understand where all the normal
Where do you think the error
import socket,time
import thread
class http():
def __init__(self):
self.socket = socket
self.port = 5000
self.buffsize = 1024
self.listen = 5
self._header = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n\r\n")
def _worker(self,socket,sleep):
# Client connect for thread worker
while True:
time.sleep(sleep)
client,address = socket.accept()
data = client.recv(1024)
if data:
client.send(self._header)
client.send(data)
client.close()
def httpHandler(self):
# Create Socket For Connection
try:
self.socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.socket.bind(('127.0.0.1',self.port))
self.socket.listen(self.listen)
self.socket.setblocking(False)
except socket.error as error:
print error
finally:
print "HTTP Server Running - 127.0.0.1:5000"
self._worker(self.socket,1)
if __name__ == "__main__":
application = http()
application.httpHandler()
When I want to run on the terminal, the error
but how can it be said there is the problem of self-
HTTP Server Running - 127.0.0.1:5000
Traceback (most recent call last):
File "/Users/batuhangoksu/http.py", line 44, in <module>
application.httpHandler()
File "/Users/batuhangoksu/http.py", line 40, in httpHandler
self._worker(self.socket,1)
File "/Users/batuhangoksu/http.py", line 22, in _worker
client,address = socket.accept()
AttributeError: 'module' object has no attribute 'accept'
Use self.socket, not socket:
client,address = self.socket.accept()
socket is the name of the module. self.socket is a socket._socketobject, the value returned by a call to socket.socket. Verily, there are too many things named "socket" :).
I suggest changing self.socket to something else to help separate the ideas.
You also need to save the return value when you call socket.socket. Currently, you have
self.socket = socket
which sets the instance attribute self.socket to the module socket. That's not useful, since you can already access the module with plain old socket. Instead, use something like
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
import multiprocessing as mp
import socket
import time
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
def server():
header = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n\r\n")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
while True:
conn, addr = s.accept()
data = conn.recv(1024)
if not data: break
conn.send(header)
conn.send(data)
conn.close()
def client():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
sproc = mp.Process(target = server)
sproc.daemon = True
sproc.start()
while True:
time.sleep(.5)
client()