Python 2 to 3 Conversion
Wildman
best_lay at yahoo.com
Sun Feb 18 11:18:45 EST 2018
On Sun, 18 Feb 2018 20:51:18 +1100, Chris Angelico wrote:
> On Sun, Feb 18, 2018 at 4:35 AM, Wildman via Python-list
> <python-list at python.org> wrote:
>> Thanks to Chris and Ben. Your suggestions were slightly
>> different but both worked equally well, although I don't
>> understand how that can be so.
>>
>>> struct.pack('256s', ifname[:15].encode('ascii'))
>>> struct.pack('256s', ifname.encode('ascii'))
>
> Those two will be identical for short interface names, but the first
> form will truncate a longer name before encoding. I don't know what
> the ioctl will do with a really long ifname, so it's probably worth
> hanging onto the [:15] slicing.
Since the interfaces are named by the (Linux) system,
I don't think long interface names will be a problem.
Names are used like lo, eth0, wlan0, ppp0, vmnet8, etc.
But, I will keep the [:15} slicing just in case.
>> I was looking for a reliable way to determine the IP addy
>> for a given network adapter. That is what the code does
>> but I don't understand how it does it either.
>>
>> Thanks again. I will continue to research and study the
>> code in the hope I will understand it.
>
> Ah, makes sense. I'd probably do something like this:
>
>>>> import socket
>>>> s = socket.socket(type=socket.SOCK_DGRAM)
>>>> s.connect(("8.8.8.8", 53))
>>>> s.getsockname()[0]
> '192.168.0.19'
Brief background... I am working on a project that reports
Linux system info and lan is part of it. To start with I
was using code similar to the above but, with the help of
a few testers in some of the Linux newsgroups, I found it
did not work correctly in all situations such as 'live'
sessions. So I started looking for an alternative.
> But that's only going to show one (uplink) address. If I needed to get
> ALL addresses for ALL network adapters, I'd either look for a library,
> and if one wasn't easily found, I'd shell out to the "ip" command and
> parse its output. :)
>
> ChrisA
I considered using the "ip" command but I prefer not to
depend on external programs if I can get around it. I
know that might be considered silly but that's just me.
Thanks for your input.
--
<Wildman> GNU/Linux user #557453
The cow died so I don't need your bull!
More information about the Python-list
mailing list