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

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.

Related

How to send requests to another computer with python

Basically I have a chatroom which I'm going to turn into a network (I know it doesn't sound like it makes a lot of sense) but basically I was wondering if I could have a python script capture all outgoing requests on a computer and instead send it to another computer (c2). I then want c2 to make the request on it's own. This is a watered down explanation of what I'm doing but any help will be great!
Firstly, you can set up a remote machine and get its IP address. On the remote machine you can set up this code:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('*CHANGE TO SERVER IP*', portnumber)
print("Starting on %s port %s" % server_address)
sock.bind(server_address)
sock.listen(1)
while True:
connection, client_address = sock.accept()
try:
data = connection.recv(999)
# You have received the data, do what you want with it.
except:
connection.close()
And on the client machine:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('*INSERT SERVER IP*', portnumber)
print('Connecting to %s port %s' % server_address)
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(server_address)
message=input('Message: ')
if message=='quit':
break
sock.sendall(message)
except:
break
sock.close()
The server side code also works as client side for receiving information.

Send and receive messages on same port? Peer to peer message app python

I'm trying to create a peer to peer message app, I understand I need each instance of the app to be both a server and a client as I've got for the below code but I'm wondering how to set up the ports, can I send and receive messages on the same port?
The below code is one instance of the app, I can communicate with another version but I have to set the other version to send messages on port 9000 and receive messages on 6190. This won't work going forward as how would a third user connect?
Current situation:
User 1: Receives on 9000, sends on 6190
User 2: Receives on 6190, sends on 9000
import socket
import time
import threading
global incoming
def server_socket(): #call server_socket() in build method?
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9000))
s.listen(1)
host_name = socket.gethostname()
ip_address = socket.gethostbyname(host_name)
print("IP address is: ", ip_address)
except socket.error as e:
print("Socket Error !!", "Unable To Setup Local Socket. Port In Use")
while True:
conn, addr = s.accept()
incoming_ip = str(addr[0])
data = conn.recv(4096)
data = data.decode('utf-8')
print("message recieved is: ", data)
conn.close()
s.close()
def client_send_message():
message = "Hello World"
message = message.encode('utf-8')
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
c.connect(("127.0.0.1", 6190))
except Exception as e:
print("Connection Refused", "The Address You Are Trying To Reach Is Currently Unavailable")
try:
c.send(message)
except Exception as e:
print(e)
c.close()
t = threading.Thread(target=server_socket)
t.start()
for i in range(5):
time.sleep(30)
client_send_message()
You currently use TCP and with this design you need a separat socket for each client. You can exchange data on this socket in both directions though. More common for peer to peer networks is UDP: here you can use a single socket to recvfrom data from arbitrary clients and sendto data to arbitrary clients.

Python socket : Error receive data

I write a network application. The server has ability to find client base on given subnet. If the client receive authentication message from server, it will respond to server. Everything working good but server, it can't receiver from client.
Client :
def ListenServer():
# Listen init signal from Server to send data
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
# UDP Socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, PORT))
data, addr = s.recvfrom(1024)
if data == 'Authen':
SocketConnect(addr[0])
def SocketConnect(HOST):
# Connect to Server to send data
print HOST
PORT = 50008 # The same port as used by the server
# Create Socket
print "Create Socket"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print "Error creating socket: %s" %e
sys.exit(1)
# Connect
print "Connect"
try:
s.connect((HOST, PORT))
except socket.error, e:
print "Connection error: %s" %e
sys.exit(1)
# Send Data
print "Send Data"
try:
s.sendall('Hello, world')
except socket.error, e:
print "Error sending data: %s" % e
sys.exit(1)
# Close Socket
s.close()
print "Close Socket"
ListenServer()
Server :
from netaddr import IPAddress
import socket
import sys
import ipaddress
import time
def FindAgent():
PORT = 50007 # Port use to find Agent
#Find broadcast address
"""IPAddress("255.255.255.0").netmask_bits() #Convert Subnet Mask to Prefix Length, Result is 24"""
try :
HOST = str(ipaddress.ip_network(u'192.168.10.0/24')[-1])
except ValueError as e :
"""e = sys.exc_info()[0] # Find Exception you need"""
print e
# UDP client
MESSAGE = "Authen"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for x in range(0,2):
sock.sendto(MESSAGE, (HOST, PORT))
def ListenClient():
# Listen Client sent data
HOST = socket.gethostbyname(socket.gethostname())
PORT = 50008
# TCP socket
# Create Socket
print "Create Socket"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print "Error creating socket: %s" %e
sys.exit(1)
# Bind
print "Bind"
try:
s.bind((HOST, PORT))
except socket.error, e:
print "Error bind: %s" %e
sys.exit(1)
# Listen
print "Listen"
try:
s.listen(10)
except socket.error, e:
print "Error listen: %s" %e
sys.exit(1)
# Accept data from client
print "Accept data from client"
try:
conn, addr = s.accept()
data = s.recv(1024)
except socket.error, e:
print "Error listen: %s" %e
sys.exit(1)
print data
s.close()
FindAgent()
ListenClient()
Error on Server :
Create Socket
Bind
Listen
Accept data from client
Error listen: [Errno 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
[Finished in 0.8s with exit code 1]
[shell_cmd: python -u "C:\Users\Win7_Lab\Desktop\Server.py"]
[dir: C:\Users\Win7_Lab\Desktop]
[path: C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]
Without the line data = s.recv(1024) on Server, it working fine. But with it, the error show up. Can anybody please tell me why it happen ?
The crash come from s.recv(1024) as you said it's because the recieve (.recv()) methode on your server need to be called on the client connection.
Follow this example : here
Server file :
conn, addr = s.accept()
data = conn.recv(1024)
Client file :
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
As you see the client recieve data from socket (server).
And server recieve data from client connection.
Hope that was usefull.
Edit add some examples links.
You can find what you want in these tutorial:
How to use socket
How to create server with socket and select
Example client server giving time
Example chat client server

Python could not receive from server after sending message over

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.

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.

Categories