Determine the IP address of an eth interface

Michael Amrhein michael at adrhinum.de
Thu Jan 19 10:40:53 CET 2006


billie wrote:
> Hi all. I'm searching for a module that permits me to low-level interact
> with ethernet interfaces of my system.
> I would like to determine at least the first of the followings values:
> 
> 1 - IP address assigned to the interface
> 2 - subnet mask
> 3 - default gateway
> 4 - primary and secondary dns
> 5 - default wins server
> 6 - mac address
> 7 - broadcast address
> 
> On python cookbook I found this usefuls script that returns the IP address
> of a specified interface but it only works on unix platforms. I was 
> wondering if exist a specific module that could solve this kind of
> problems.
> Best regards.
> 
> 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])
> 
>>>> get_ip_address('lo')
> '127.0.0.1'
> 
>>>> get_ip_address('eth0')
> '38.113.228.130'
> 

On win... you may call ipconfig: os.popen('ipconfig /all','r')
- if ipconfig on your default path, otherwise specify full path -
and retrieve the information you want from the output.

Have fun
Michael



More information about the Python-list mailing list