简体   繁体   中英

how can i solve this connection error and typeerror

I am trying to create a simple traceroute app. I want to save the ip s to rota file. But i am taking errors, i dont know why. Errors:

connection error
Traceback (most recent call last):
  File "rota.py", line 30, in <module>
    f.write('\n' + str(addr[0]))
TypeError: 'NoneType' object is not subscriptable

My Code:

import sys
import socket

dst = sys.argv[1]
dst_ip = socket.gethostbyname(dst)
port = 42424
ttl = 1
max_hop = 30
f = open('rota.txt','w')
timeout = 0.2

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,port))

    addr = None

    try:
        data , addr = receiver.recvfrom(1024)
    except socket.error:
        print('connection error')

    f.write('\n' + str(addr[0]))

The error comes because you are slicing addr object, but it's not iterable so you cannot do it like so.

In this case, you are setting addr = None and later you are setting the value inside the try block. If python is not able to perform data, addr = receiver.recvfrom(1024) (which is the case) it raises an error, but as it's inside the try-except structure, it can continue but addr continues to be set as addr = None .

So you are trying to do None[0] and as you might know, None is unsubscriptable.

So you must do:

# ...

sender.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
sender.sendto(b'',(dst,port))

try:
    data , addr = receiver.recvfrom(1024)
    f.write('\n' + str(addr[0]))
except socket.error:
    print('connection error')

as you don't need to create addr before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM