0

I used python netdiscover tool to obtain which devices are connected to my local network, and I want to write their IP addresses into a text file. To do this, I want to take out IP addresses from the following list which is the product of netdiscover:

lst = [{'ip': b'192.168.1.1', 'mac': b'40:35:c1:8e:7e:78'},
       {'ip': b'192.168.1.108', 'mac': b'44:a0:50:56:22:99'},
       {'ip': b'192.168.1.101', 'mac': b'ff:5b:4b:46:70:67'},
       {'ip': b'192.168.1.100', 'mac': b'6a:ef:3b:58:8f:f0'},
       {'ip': b'192.168.1.102', 'mac': b'46:72:b0:ef:3c:a8'}, 
       {'ip': b'192.168.1.104', 'mac': b'58:c2:f5:b1:65:42'}]

The IP addresses are bytes object. To convert them to a string so that I can write them to a file, I used the following code:

for i in lst:
    f=i.get("ip")
    f1=str(f)
    f2=f1.partition("b")
    print(f2[2])

This code gave me what I desire, but it seems ridiculous to me. Is there a more elegant way to take out the IP addresses from list?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 1
    How so? Your `i['ip']` values are `bytes` objects. You want to convert them to strings. Answers to that question show you the way to do what you are asking. – Pranav Hosangadi Jan 12 '23 at 17:38

1 Answers1

0

With simple list comprehension and bytes.decode function:

ips = [d['ip'].decode() for d in lst]
print(ips)

['192.168.1.1', '192.168.1.108', '192.168.1.101', '192.168.1.100', '192.168.1.102', '192.168.1.104']
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • 2
    Again, please try to understand what OP is actually asking and direct them to a duplicate when one exists instead of adding an answer – Pranav Hosangadi Jan 12 '23 at 17:36