i am trying to create a proxy server script with python when i run it i have this arror messages please can i know what are the mistakes i've done and how to avoid them (i sow the script on a site)
how the script looks like !
import socket
from thread import *
import sys
host = ""
port = 91
def start():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
print "[+] listening ..."
while True:
try:
connection, address = s.accept()
data = connection.recv(1024)
start_new_thread(conn_string, (data, connection))
except KeyboardInterrupt:
print "\n\nclosing !"
def conn_string(data, con):
webserver = ""
portserver = 0
f_li = data.split('\n')[0]
lien = f_li.split(' ')[1]
http_pos = lien.find("://")
if http_pos == -1:
url = lien
else:
url = lien[(http_pos+3):]
port_pos = url.find(':')
if port_pos == -1:
portserver = 80
else:
portserver = url[(port_pos+1):]
s_pos = url.find('/')
if s_pos == -1:
webserver = url
else:
webserver = url[:(s_pos)]
proxy_server(webserver, portserver, data, con)
def proxy_server(webserver, portserver, data, con):
print webserver
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((webserver, int(portserver)))
s.send(data)
while True:
red = s.recv(8192)
if len(red) > 0:
con.send(red)
start()
this is one of the error messages that i have !
Unhandled exception in thread started by <function conn_string at 0x0248CEF0>
Traceback (most recent call last):
File "C:\Users\none2\Desktop\Nouveau dossier\Target.py", line 52, in conn_stri
ng
proxy_server(webserver, portserver, data, con)
File "C:\Users\none2\Desktop\Nouveau dossier\Target.py", line 57, in proxy_ser
ver
s.connect((webserver, int(portserver)))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 11004] getaddrinfo failed
can you replace
start_new_thread(conn_string, (data, connection))
line with
start_new_thread(conn_string(data, connection))
tried running the same file, it seems above one is the only error
Related
I'm new to python, and I came across this code, but It come up with an error (the title)
I run py server_chat.py (ip) 21567
and py client.py (ip) 21567
This is my code in chat_server.py
import socket
import select
from _thread import *
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if len(sys.argv) != 3:
print("Correct usage: script, IP address, port number")
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.bind((IP_address, Port))
server.listen(100)
list_of_clients=[]
def clientthread(conn, addr):
conn.send("Welcome to this chatroom!")
while True:
try:
message = conn.recv(2048)
if message:
print("<" + addr[0] + "> " + message)
message_to_send = "<" + addr[0] + "> " + message
broadcast(message_to_send,conn)
else:
remove(conn)
except:
continue
def broadcast(message,connection):
for clients in list_of_clients:
if clients!=connection:
try:
clients.send(message)
except:
clients.close()
remove(clients)
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
while True:
conn, addr = server.accept()
list_of_clients.append(conn)
print(addr[0] + " connected")
start_new_thread(clientthread,(conn,addr))
conn.close()
server.close()
And I get this error for chat_server.py (it says connected, but then gives an error):
(ip) connected!
Exception ignored in thread started by: <function clientthread at 0x0000019F8B0AE040>
Traceback (most recent call last):
line 26, in clientthread
conn.send("Welcome to this chatroom!")
TypeError: a bytes-like object is required, not 'str'
This is my code in client.py
import socket
import select
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
print ("Correct usage: script, IP address, port number")
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.connect((IP_address, Port))
while True:
sockets_list = [sys.stdin, server]
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == server:
message = socks.recv(2048)
print (message)
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
server.close()
And I get this error for client.py
Traceback (most recent call last):
line 27, in <module>
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
OSError: [WinError 10038] An operation was attempted on something that is not a socket is not a socket
Please help, I don't know what to do.
I try to make a chat on Python3. Here is my code:
import socket
import threading
print("Server starts working")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 57054))
sock.listen(2)
conn, addr = sock.accept()
def get_message():
while True:
data = sock.recv(1024).decode()
if len(data) != 0:
print("Some guy: ", data)
def send_message():
while True:
message = input()
if len(message) != 0:
message = str.encode(message)
sock.send(message)
print("You: ", message)
def run():
get_message_thread = threading.Thread(target=get_message())
send_message_thread = threading.Thread(target=send_message())
get_message_thread.daemon = True
send_message_thread.daemon = True
get_message_thread.start()
send_message_thread.start()
run()
sock.close()
But after the execution and sending a message from other client I get an error message:
Server starts working
Traceback (most recent call last):
File "/home/ptrknvk/Documents/Study/Python/chat/chat.py", line 40, in <module>
run()
File "/home/ptrknvk/Documents/Study/Python/chat/chat.py", line 30, in run
get_message_thread = threading.Thread(target=get_message())
File "/home/ptrknvk/Documents/Study/Python/chat/chat.py", line 15, in get_message
data = sock.recv(1024).decode()
OSError: [Errno 107] Transport endpoint is not connected
Process finished with exit code 1
I've read, that there are some troubles with sock.accept(), but everything's alright here, as I think.
Your program has many flaws. As zondo mentioned, you are incorrectly passing the target. They should be like threading.Thread(target=get_message). Second problem is, you should use conn (and not sock) for sending and receiving data. Third problem is, main thread was blocking at accept call and will wait for the connection. But soon as it accepts a connection, it will exit. From the main thread, you should wait for get_message_thread and send_message_thread. Try the modified code:
import socket
import threading
print("Server starts working")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 57054))
sock.listen(2)
conn, addr = sock.accept()
def get_message():
while True:
data = conn.recv(1024).decode()
if len(data) != 0:
print("Some guy: ", data)
def send_message():
while True:
message = input()
if len(message) != 0:
message = str.encode(message)
conn.send(message)
print("You: ", message)
def run():
get_message_thread = threading.Thread(target=get_message)
send_message_thread = threading.Thread(target=send_message)
get_message_thread.daemon = True
send_message_thread.daemon = True
get_message_thread.start()
send_message_thread.start()
get_message_thread.join()
send_message_thread.join()
run()
sock.close()
I was working on a networked chat by following a tutorial. I have two modules, chatServer.py3 and chatClient.py3. On starting the server and then a client and attempting to send a message I get the following error:
Traceback (most recent call last): File "chatClient.py3", line 49,
in <module>
Main() File "chatClient.py3", line 38, in Main
s.sendto(alias+": "+message, server)
socket.error: [Errno 57] Socket is not connected
Please keep in mind that I am a rookie and therefore I would appreciate if the solutions along with their explanations were simplistic.
chatClient.py3
import socket, time, threading
tLock = threading.Lock()
shutdown = False
def recieveing(name,sock):
locked = False
while not shutdown:
try:
tLock.aquire()
locked = True
while True:
data , addr = sock.recv(1024)
print str(data)
except:
pass
finally:
if locked:
tLock.release()
def Main():
host = '127.0.0.1'
port = 0
server = ('127.0.0.1', 5000)
s = socket.socket()
s.bind((host,port))
s.setblocking(0)
rT = threading.Thread(target=recieveing,args=("RecivedThread",s))
rT.start()
alias = raw_input("Name: ")
message = raw_input(alias+"-> ")
while message != "q":
if message != "":
s.sendto(alias+": "+message, server)
tLock.aquire()
message = raw_input(alias+"-> ")
tLock.release()
time.sleep(0.2)
shutdown = True
rT.join()
s.close()
if __name__ == '__main__':
Main()
chatServer.py3
import socket,time
host = '127.0.0.1'
port = 5000
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)
quitting = False
print "Server Started."
while not quitting:
try:
data, addr = s.recvfrom(1024)
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
print time.ctime(time.time()) + str(addr) + " : : "+str(data)
for client in clients:
s.sendto(data, client)
except:
pass
s.close()
You don't need to bind your client to the host and port. The bind command defines where the server needs to listen. The client needs to connect to the server. Like this:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server = ('127.0.0.1', 5000)
s.connect(server)
Here is the serve code:
from socket import *
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
try:
while True:
print 'Wait for connection...'
tcpCliSock, addr = tcpSerSock.accept()
print '...connnet from:', addr
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send('[%s] %s' % (ctime(), data))
tcpCliSock.close()
except (EOFError, KeyboardInterrupt):
tcpSerSock.close()
Here is the client code:
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = raw_input(">")
if not data:
break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print data
break
tcpCliSock.close()
When I run serve code, it shows:
Traceback (most recent call last):
File "G:/python/tcpServ&tcpClnt/tsTserv.py", line 22, in <module>
data = tcpCliSock.recv(BUFSIZ)
File "C:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
But client could still get the information. Then I changed the code in socket.py, it worked! But I don't know why.
PS. I changed:
class _closedsocket(object):
__slots__ = []
def _dummy(*args):
raise error(EBADF, 'Bad file descriptor')
to this:
class _closedsocket(object):
__slots__ = []
def _dummy(*args):
pass
The error occurs because you call recv() of the afore closed socket. Sequence of execution:
…
data = tcpCliSock.recv(BUFSIZ) # data from tcpCliSock.send(data) is received
# not true: if not data:
# skipped: break
tcpCliSock.send('[%s] %s' % (ctime(), data)) # reply data is sent to client
tcpCliSock.close() # the socket is closed!
while True: # the loop is reiterated
data = tcpCliSock.recv(BUFSIZ) # the closed socket is used!
Perhaps you just by mistake indented the tcpCliSock.close() wrongly. If you outdent it, all works:
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send('[%s] %s' % (ctime(), data))
tcpCliSock.close()
Then I changed the code in socket.py, it worked! But I don't know why.
By changing raise … to pass, you just swept the error under the carpet.
I want to start a project to learn python, and I chose to write a simple web proxy.
In some case, some thread seems get a null request, and python rasie exception:
first_line: GET http://racket-lang.org/ HTTP/1.1
Connect to: racket-lang.org 80
first_line:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "fakespider.py", line 37, in proxy
url = first_line.split(' ')[1]
IndexError: list index out of range
first_line: first_line: GET http://racket-lang.org/plt.css HTTP/1.1GET http://racket-lang.org/more.css HTTP/1.1
Connect to:Connect to: racket-lang.orgracket-lang.org 8080
My code was simple.
I don't know what's going on, any help would be appreciated:)
from threading import Thread
from time import time, sleep
import socket
import sys
RECV_BUFFER = 8192
DEBUG = True
def recv_timeout(socks, timeout = 2):
socks.setblocking(0);
total_data = []
data = ''
begin = time()
while True:
if total_data and time() - begin > timeout:
break
elif time() - begin > timeout * 2:
break
try:
data = socks.recv(RECV_BUFFER)
if data:
total_data.append(data)
begin = time()
else:
sleep(0.1)
except:
pass
return ''.join(total_data)
def proxy(conn, client_addr):
request = recv_timeout(conn)
first_line = request.split('\r\n')[0]
if (DEBUG):
print "first_line: ", first_line
url = first_line.split(' ')[1]
http_pos = url.find("://")
if (http_pos == -1):
temp = url
else:
temp = url[(http_pos + 3):]
port_pos = temp.find(":")
host_pos = temp.find("/")
if host_pos == -1:
host_pos = len(temp)
host = ""
if (port_pos == -1 or host_pos < port_pos):
port = 80
host = temp[:host_pos]
else:
port = int((temp[(port_pos + 1):])[:host_pos - port_pos - 1])
host = temp[:port_pos]
print "Connect to:", host, port
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(request)
data = recv_timeout(s)
if len(data) > 0:
conn.send(data)
s.close()
conn.close()
except socket.error, (value, message):
if s:
s.close()
if conn:
conn.close()
print "Runtime error:", message
sys.exit(1)
def main():
if len(sys.argv) < 2:
print "Usage: python fakespider.py <port>"
return sys.stdout
host = "" #blank for localhost
port = int(sys.argv[1])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(50)
except socket.error, (value, message):
if s:
s.close()
print "Could not open socket:", message
sys.exit(1)
while 1:
conn, client_addr = s.accept()
t = Thread(target=proxy, args=(conn, client_addr))
t.start()
s.close()
if __name__ == "__main__":
main()
The stack trace you see says everything:
url = first_line.split(' ')[1]
IndexError: list index out of range
Apparently the result of splitting variable first_line is not a list having more than one element, as you assumed. So it contains something different than you expected. To see what it actually contains just print it out:
print first_line
or use a debugger.