Python Forum
Find IP of a device on a local network - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Find IP of a device on a local network (/thread-1485.html)



Find IP of a device on a local network - mrburnzie - Jan-06-2017

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!


RE: Find IP of a device on a local network - Larz60+ - Jan-06-2017

Read the docs: https://docs.python.org/3/library/socket.html


RE: Find IP of a device on a local network - wavic - Jan-07-2017

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


RE: Find IP of a device on a local network - Larz60+ - Jan-07-2017

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'])



RE: Find IP of a device on a local network - Ofnuts - Jan-08-2017

(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...