Just to be clear: I just started Python 2 weeks ago but I'm a C#, ASP, PHP, JavaScript developer.
I just started a new project with Python and PyQt and I want my project to be a server that will be able to communicate with other instance of this server on other computers.
So, I need to get computers IP address and host name.
First, I thought about using the MSDOS "net view" command but this was before trying this command at my job and seeing that this could take around ~15s (which I think is too slow).
I had this idea from: https://stackoverflow.com/a/15497083/1598891
Also, the "net view" command can return computers that are no longer on the network and cause exception when trying to get their IP addresses by host name (which also slows down the process each time a computer cannot be accessed).
My Question: Is there a way to get all computers IP and Host Name on the Local network without passing by net view
on Windows because net view
could be a slow operation?
Also, is there a way to only get computers that are running my application? (so it would be faster)
Thanks in advance
For the hostname and ip of the localhost you could use the socket module and gethostname, and gethostbyname methods:
import socket
hostname = socket.gethostname()
IP = socket.gethostbyname(hostname)
If you want to get the IP address of the host on which the python script is running, then the answer provided by user2096338 is the way to go.
In order to discover all the computers on a network within a LAN you can use scapy. https://github.com/bwaldvogel/neighbourhood/blob/master/neighbourhood.py is a link that I found while browsing a similar SO question; which discovers all computers within a network (LAN).
If you want to ensure that the above script returns only those computers that are running your server - then there are multiple ways to do so, listed below in order of portablility
In my opinion, method 1 is the safest and portable, since it prevents the opening up of unnecessary ports( like method 3) which are security holes (depending on whose context your python script runs). It also does not depend on the availability of the WMI service on the remote hosts ( some systems may have WMI disabled).
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With