Use Python to detect IP address usage in your LAN

Source: Internet
Author: User
Tags emit

In the process of setting up the test environment, we often need to assign static IP address to the server, because it is unclear which IP address is idle in the current LAN, so we often need one to try to find an available IP. When working in a previous company, a tool was used to detect IP usage, but it was an internal tool that could not be obtained. So I thought, why not develop one yourself?

To do it, the development environment uses PYTHON3.6+PYQT5. If your environment is not the same, it may fail to run.

Source Address: https://github.com/donglin-zhang/easyPing--python3.6

1. Interface design

Interface with Qtdesigner to draw, first to a prototype diagram below, each can only test a network segment of the IP occupancy, 0-255 small panes used to show the use of IP address, the default is gray, after the program, the IP address has been used to display green, the IP address is not used to display red.

  

When doing the interface, 255 small panes are really human life, so just draw a window frame, the UI file into a Python source code, and manually write their own codes to implement the 255 pane layout. The code snippet is as follows:

Self.gridlayout =qtwidgets.qgridlayout (self.widget1) self.gridlayout.setContentsMargins (0, 0, 0, 0) Self.gridlayout.setO Bjectname ("GridLayout") self.gridlayout.setSpacing (7) Self.label_list=[] List_index=0 forIinchRange (1, 17):             forJinchRange (1, 17): Label=Qtwidgets.qlabel (Self.widget1) label.setminimumsize (Qtcore.qsize (32, 15)) Label.setstylesheet ("Background-color:rgb (203, 203, 203);") label.setalignment (QtCore.Qt.AlignCenter) Label.settext (QtCore.QCoreApplication.transl Ate ("myping", str (list_index))) Self.label_list.append (label) self.gridlayout.addWidget (label, I-1, J-1, 1, 1) List_index+ = 1

  2, ping function implementation

  There are many ways to implement Ping, the most common of course is to call the system's own ping function to achieve.

The way in which Python executes system commands is Os.system (), Os.popen (), subprocess, and so on, as shown in the Python3.6 manual that subprocess modules are used to replace functions such as Os.system. So we also use the Subprocess module to call Ping

python3.5, Subprocess adds a run function, the run function creates a subprocess to run the command to execute, returns a completedprocess instance, which basically handles all scenarios, and run is a layer of subprocess.popen Packaging.

python3.5 following functions such as Subprocess.call (), Subprocess.check_call () can be used to achieve the same functionality, see the Python manual

defGet_ping_result (self, IP):" "Check if the corresponding IP is occupied" "Cmd_str="Ping {0}-n 1-w". Format (IP) detached_process= 0x00000008#do not create a CMD window    Try: Subprocess.run (cmd_str, Creationflags=detached_process, Check=true)#for Windows systems only    exceptsubprocess. Calledprocesserror as Err:self._ping_signal.emit (False, IP)Else: Self._ping_signal.emit (True, IP)

Description

By default, when you use Subprocess.run () to ping the command, a cmd window pops up, and when 256 threads are running together, the full screen window is very sour ...

Under Windows systems, you can pass in the Creationflags parameter to enable subprocess to create a child process that does not generate a console

Reference Link: Https://stackoverflow.com/questions/7006238/how-do-i-hide-the-console-when-i-use-os-system-or-subprocess-call

When the check parameter is true, the function detects whether the execution result is 0 (where 0 means execution succeeds) and nonzero throws an exception.

3. Multithreading

When using PYQT for GUI programming, if involves the operation which needs the long time background to run, generally need to use the multithreading way, otherwise the interface will block, until the background runs the end, causes the program to die the illusion.

In this program implementation, to achieve the ping operation of 256 addresses, if single-threaded operation, certainly half a day can not get results, so we assign a thread for each IP address, up to 256 threads concurrently running, 1-2 seconds of time to get the entire network segment IP address occupancy

The core code for multithreaded implementations is as follows:

defstart_ping (self):" "Start Multithreading" "self.reset_ui () StartIP= Self.ui.startIP.text (). Split ('.') EndIP= Self.ui.endIP.text (). Split ('.') Tmp_ip=StartIP pthread_list= []     forIinchRange (int (startip[3]), int (endip[3]) + 1): tmp_ip[3] =STR (i) IP='.'. Join (TMP_IP) Pthread_list.append (threading. Thread (Target=self.get_ping_result, args=(IP,)))  forIteminchPthread_list:item.setDaemon (True) Item.Start ()

The child thread notifies the main program of the execution result by transmitting the signal, and the final main program renders the interface according to the result of the operation.

All source code can be downloaded to GitHub, the link to interview the article head.

Use Python to detect IP address usage in your LAN

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.