On Sat, Feb 17, 2018 at 4:15 PM, Wildman via Python-list <python-list@python.org> wrote: > I have a bit of code I found on the web that will return > the ip address of the named network interface. The code > is for Python 2 and it runs fine. But, I want to use the > code with Python 3. Below is the code followed by the error > message. Suggestions appreciated. > > #!/usr/bin/env python3 > > import socket > import fcntl > import struct > > def get_ip_address(ifname): > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > return socket.inet_ntoa(fcntl.ioctl( > s.fileno(), > 0x8915, # SIOCGIFADDR > struct.pack('256s', ifname[:15]) > )[20:24]) > print(get_ip_address("eth0")) > print(get_ip_address("lo")) > > > Traceback (most recent call last): > File "./test.py", line 14, in <module> > print(get_ip_address("eth0")) > File "./test.py", line 12, in get_ip_address > struct.pack('256s', ifname[:15]) > struct.error: argument for 's' must be a bytes object
The easiest way is to encode it to ASCII: struct.pack('256s', ifname[:15].encode('ascii')) But you may want to see if there's a completely different way to do what you're looking at. I'm not sure what this is doing, so I can't advise more specifically. ChrisA -- https://mail.python.org/mailman/listinfo/python-list