how can i fix addr is not defined in python - python

I want to make a app like traceroute. I am trying to find routers IP adresses which i passed until i reach the machine and save them in my rota file. But i am taking addr is not defined error. I searched , usually they are giving addr = None but this is causing -'NoneType' object is not subscriptable- error. How can i fix it ?
This is my code:
import sys
import socket
dst = sys.argv[1]
dst_ip = socket.gethostbyname(dst)
f = open("rota.txt","w")
timeout = 0.2
max_hops = 30
ttl=1
port = 11111
while True:
receiver = socket.socket(family=socket.AF_INET,type=socket.SOCK_RAW,proto=socket.IPPROTO_ICMP)
receiver.settimeout(timeout)
receiver.bind(('',port))
sender = socket.socket(family=socket.AF_INET,type=socket.SOCK_DGRAM,proto=socket.IPPROTO_UDP)
sender.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
sender.sendto(b'',(dst_ip,port))
try:
data, addr = receiver.recvfrom(512)
f.write('\n' + str(addr[0]))
except socket.error:
pass
finally:
receiver.close()
sender.close()
ttl += 1
if ttl > max_hops or addr[0] == dst_ip:
break
And my errors:
Traceback (most recent call last):
File "rota.py", line 33, in <module>
if ttl > max_hops or addr[0] == dst_ip:
NameError: name 'addr' is not defined

Related

python socket OSError: [WinError 10038] an operation was attempted on something that is not a socket

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.

TypeError: descriptor 'bind' requires a '_socket.socket' object but received a 'tuple'

I am trying to make a simple socketing server and client by Python.But when I run the Server code,It shows
Traceback (most recent call last):
File "G:/Python/pyProject/TestOfConnection/socket_sever_pickle.py", line 33, in <module>
Server_PIC(Server_IP, Server_Port)
File "G:/Python/pyProject/TestOfConnection/socket_sever_pickle.py", line 8, in Server_PIC
socket.bind((ip,port))
TypeError: descriptor 'bind' requires a '_socket.socket' object but received a 'tuple'
Here it is:
from socket import *
from io import BytesIO
import pickle
def Server_PIC(ip, port):
socket_obj = socket(AF_INET, SOCK_STREAM)
socket.bind((ip,port))
socket_obj.listen(10)
file_no = 1
while True:
connection, address = socket_obj.accept()
print("server connect by:", address)
recieved_message = b''
recieved_message_fragment = connection.recv(1024)
while recieved_message_fragment:
recieved_message += recieved_message_fragment
recieved_message_fragment = connection.recv(1024)
try:
obj = pickle.loads(recieved_message)
print(obj)
except EOFError:
file_name = 'recv_image_' + str(file_no) + '.bmp'
recv_image = open(file_name, 'wb')
recv_image.write(recieved_message)
recv_image.close()
connection.close()
if __name__ == '__main__':
Server_IP = '0.0.0.0'
Server_Port = 6666
Server_PIC(Server_IP, Server_Port)
I also try to Google this question and modify the code,but it will cause a series of problems.
So could any of you help me figure out what is going on wiht my code. Thanks in advance!
When I modify the code,the error disappeared.
# from socket import *
import socket
from io import BytesIO
import pickle
def Server_PIC(ip, port):
# socket_obj = socket(AF_INET, SOCK_STREAM)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((ip,port))
s.listen(10)
file_no = 1
while True:
connection, address = s.accept()
print("server connect by:", address)
recieved_message = b''
recieved_message_fragment = connection.recv(1024)
while recieved_message_fragment:
recieved_message += recieved_message_fragment
recieved_message_fragment = connection.recv(1024)
try:
obj = pickle.loads(recieved_message)
print(obj)
except EOFError:
file_name = 'recv_image_' + str(file_no) + '.bmp'
recv_image = open(file_name, 'wb')
recv_image.write(recieved_message)
recv_image.close()
connection.close()
if __name__ == '__main__':
Server_IP = '0.0.0.0'
Server_Port = 6666
Server_PIC(Server_IP, Server_Port)

socket.gaierror: Errno 11004 getaddrinfo failed

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

python errno 23 - socket livestatus

I'm trying to send two queries to the server with this script, to get the MK Livestatus:
live.py
#!/usr/bin/python
socket_path = "/tmp/run/live"
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(socket_path)
# Get Hosts
hosts = s.send("GET hosts\nColumns: name\n")
s.shutdown(socket.SHUT_WR)
hosts = s.recv(1024)
hosts = [ line.split(';') for line in hosts.split('\n')[:-1] ]
hostsB = s.send("GET hosts\nColumns: name\n")
s.close()
But I get this error:
Traceback (most recent call last): File "live.py", line 13, in
hostsB = s.send("GET hosts\nColumns: name\n") socket.error:
[Errno 32] Broken pipe
I think the error is related to the command "s.shutdown(socket.SHUT_WR)". But the author says, that this is required. You will get no answer (timeout?), if you remove this line.
How can I send two queries?
SOLUTION
so ... I've written a function that does the job :-)
Function
def sendQuery(query):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(socket_path)
s.send(query)
s.shutdown(socket.SHUT_WR)
answer = ''
while True:
data = s.recv(1024)
answer += data
if len(data) < 1024:
break
s.close()
return answer
Usage
sendQuery("GET hosts\nColumns: name\n")
so ... I've written a function that does the job :-)
Function
def sendQuery(query):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(socket_path)
s.send(query)
s.shutdown(socket.SHUT_WR)
answer = ''
while True:
data = s.recv(1024)
answer += data
if len(data) < 1024:
break
s.close()
return answer
Usage
sendQuery("GET hosts\nColumns: name\n")

Python:Multi-thread not works as epected

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.

Categories

Resources