Python Forum

Full Version: Find IP of a device on a local network
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!


I'm working on a project for which I need to get a devices IP, but I know the host name aka. ID.

What kind of module should I use for this, I've tried socket but I couldn't figure it out, any help?

Thanks!
Hello!
I don't know how to do it with socket module. Yet
In [1]: import netifaces

In [2]: netifaces.ifaddresses('wlp9s0')
Out[2]: 
{2: [{'addr': '192.168.100.3',
   'broadcast': '192.168.100.255',
   'netmask': '255.255.255.0'}],
 10: [{'addr': 'fe80::8558:4664:f9bb:a914%wlp9s0',
   'netmask': 'ffff:ffff:ffff:ffff::/64'}],
 17: [{'addr': '68:17:29:8b:ea:98', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]}
May be socket.gethostbyname_ex('host_name') is what you want
From soshan on stackoverflow
>>> import socket

>>> def get_ips_for_host(host):
        try:
            ips = socket.gethostbyname_ex(host)
        except socket.gaierror:
            ips=[]
        return ips

>>> ips = get_ips_for_host('www.google.com')
>>> print(repr(ips))
('www.l.google.com', [], ['74.125.77.104', '74.125.77.147', '74.125.77.99'])
(Jan-06-2017, 05:15 PM)mrburnzie Wrote: [ -> ]Hello!


I'm working on a project for which I need to get a devices IP, but I know the host name aka. ID.

What kind of module should I use for this, I've tried socket but I couldn't figure it out, any help?

Thanks!
The hostname is "local" to the device. In a pure IP network you would have to register that name/address pair on a DNS server, on in the /etc/hosts file (Windows/Systems32/Drivers/etc/hosts on a windows system). Once you have done that the usual TCP/IP name resolution APIs will work.

If all involved machines also implement the NETBIOS protocol, there is a way to retrieve the IP adress from the NETBIOS name (WinDNS?).

Otherwise if you are using a specific port, you can iterate all the local network address until you connect...