Request Help With Byte/String Problem
Wildman
best_lay at yahoo.com
Tue Nov 29 21:20:42 EST 2016
For the purpose of learning I am writing a script that will
return different information about the Linux machine where
it is running. Sort of like the inxi utility.
Below is some code that I found that returns a list of the
network interface devices on the system. It runs as is
perfectly on Python2 but I get the error pasted below the
code when run on Python3, the desired version. I know it
has something to do with bytes vs. strings but I can' seem
to figure it out. Any help appreciated.
import array
import socket
import struct
def all_interfaces():
max_possible = 128 # arbitrary. raise if needed.
bytes = max_possible * 32
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array("B", '\0' * bytes)
outbytes = struct.unpack('iL', fcntl.ioctl(
s.fileno(),
0x8912, # SIOCGIFCONF
struct.pack('iL', bytes, names.buffer_info()[0])
))[0]
namestr = names.tostring()
lst = []
for i in range(0, outbytes, 40):
name = namestr[i:i+16].split('\0', 1)[0]
ip = namestr[i+20:i+24]
lst.append((name, ip))
return lst
def format_ip(addr):
return str(ord(addr[0])) + '.' + \
str(ord(addr[1])) + '.' + \
str(ord(addr[2])) + '.' + \
str(ord(addr[3]))
ifs = all_interfaces()
for i in ifs:
print("%12s %s" % (i[0], format_ip(i[1])))
Traceback (most recent call last):
File "./ifaces.py", line 32, in <module>
ifs = all_interfaces()
File "./ifaces.py", line 11, in all_interfaces
names = array.array("B", '\0' * bytes)
TypeError: cannot use a str to initialize an array with typecode 'B'
--
<Wildman> GNU/Linux user #557453
The cow died so I don't need your bull!
More information about the Python-list
mailing list