Wildman via Python-list <python-list@python.org> writes:

> 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"))

In Python 3, the literal ‘"eth0"’ creates a text (‘unicode’) object.

Python 3 correctly implements text as Unicode, which has no particular
representation as bytes.

You then pass that object to ‘struct.pack('256s', …)’, which (as the
error says) expects a ‘bytes’ object. A text object is incompatible with
that expectation.

If you want a sequence of bytes, perhaps you want to encode the text, to
some specified encoding. Maybe ASCII:

    struct.pack('256s', ifname.encode('ascii'))

That may be different from what you want the code to do, though. It's
not clear from the code what its intention is.

-- 
 \     “What is needed is not the will to believe but the will to find |
  `\       out, which is the exact opposite.” —Bertrand Russell, _Free |
_o__)                           Thought and Official Propaganda_, 1928 |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to