简体   繁体   中英

TypeError: str, bytes or bytearray expected, not list

So I am trying to pull some IP's from a text file and using that list in the socket connection. My issue is I keep getting the following error:

TypeError: str, bytes or bytearray expected, not list

Here is the code im using:

    import socket

     ips = open('list.txt', 'r').readlines()

     def displayType(sec_type):
       switcher = {
        0: "1",
        1: "2",
        2: "3"
       } 
       print(' type: ' + str(sec_type) + ' (' + switcher.get(sec_type,"Not defined by IETF") +')' )

    try:
       def check(ip,port):
         link = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
         link.connect((ip,int(port)))
         link_ver = link.recv(12)
         print(link_ver)

         link.send(link_ver)
         nb_sec_types = ord(link.recv(1))
         print("types: " + str(nb_sec_types))

    check(ips,"80")

If anyone has an idea on how to use the ip's from the list that would be great.

Change

check(ips, "80) 

for

for ip in ips: 
    check(ip, "80) 

link.connect expected a unique ip and you're passing a list of ips.

The method readlines() reads until EOF and returns a list containing the lines. So you are getting a list in ips. You will need to iterate over this list and call check() on each iteration.

Also, you have used try block without except or finally . This will result into error.

You can put catch() inside the try-except block as:

try:
 catch(ip, port)
except Exception as e:
 print(str(e))

You must first convert the string that contains the IP address into a byte or a string of bytes and then start communicating. According to the code below, your error will be resolved. Make sure your code is working correctly overall.

string = '192.168.1.102'
new_string = bytearray(string,"ascii")
ip_receiver = new_string
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(text.encode(), (ip_receiver, 5252))

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