Python obtains the ip address of the connectable host in the local area network

Use python to get the ip address of the host that can be connected in the entire LAN:

The whole idea is

1. Get the ip address of my machine first

2. After getting my local IP, intercept the last segment of the IP and keep the previous part of the network segment information

3. Invoke the cmd command, cycle from 1 to 255 times to 255 to ping the ip that can be pinged in the entire network segment

Judge whether it can be pinged by Ping TTL greater than 0

4. Finally get an ip address that can be pinged

# -*- coding: utf-8 -*-

import platform
import os
import time
import threading
import socket

live_ip = 0


def get_os():
    os = platform.system()
    if os == "Windows":
        return "n"
    else:
        return "c"


def ping_ip(ip_str):
    cmd = ["ping", "-{op}".format(op=get_os()),
           "1", ip_str]
    output = os.popen(" ".join(cmd)).readlines()
    for line in output:
        if str(line).upper().find("TTL") >= 0:
            print("ip: %s 在线" % ip_str)
            global live_ip
            live_ip += 1
            break


def find_ip(ip_prefix):
    '''''
    给出当前的ip地址段 ,然后扫描整个段所有地址
    '''
    threads = []
    for i in range(1, 256):
        ip = '%s.%s' % (ip_prefix, i)
        threads.append(threading.Thread(target=ping_ip, args={ip, }))
    for i in threads:
        i.start()
    for i in threads:
        i.join()


def find_local_ip():
    """
    获取本机当前ip地址
    :return: 返回本机ip地址
    """
    myname = socket.getfqdn(socket.gethostname())
    myaddr = socket.gethostbyname(myname)
    return myaddr


if __name__ == "__main__":
    print("开始扫描时间: %s" % time.ctime())
    addr = find_local_ip()
    args = "".join(addr)
    ip_pre = '.'.join(args.split('.')[:-1])
    find_ip(ip_pre)
    print("扫描结束时间 %s" % time.ctime())
    print('本次扫描共检测到本网络存在%s台设备' % live_ip)

operation result:

开始扫描时间: Sun Apr 26 00:10:28 2020
ip: 192.168.1.11 在线
ip: 192.168.1.6 在线
ip: 192.168.1.2 在线
ip: 192.168.1.3 在线
ip: 192.168.1.1 在线
ip: 192.168.1.4 在线
ip: 192.168.1.100 在线
ip: 192.168.1.255 在线
扫描结束时间 Sun Apr 26 00:10:32 2020
本次扫描共检测到本网络存在8台设备

At this point, we have obtained all the connectable networks in the entire local area network.

Guess you like

Origin blog.csdn.net/u012798683/article/details/105760065