List of IP addresses/hostnames from local network in Python

前端 未结 10 2430
暗喜
暗喜 2020-12-01 00:05

How can I get a list of the IP addresses or host names from a local network easily in Python?

It would be best if it was multi-platform, but it needs to work on Mac

10条回答
  •  青春惊慌失措
    2020-12-01 00:41

    I found this network scanner in python article and wrote this short code. It does what you want! You do however need to know accessible ports for your devices. Port 22 is ssh standard and what I am using. I suppose you could loop over all ports. Some defaults are:

    linux: [20, 21, 22, 23, 25, 80, 111, 443, 445, 631, 993, 995]
    windows: [135, 137, 138, 139, 445]
    mac: [22, 445, 548, 631]
    
    import socket
    
    def connect(hostname, port):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)
        result = sock.connect_ex((hostname, port))
        sock.close()
        return result == 0
    
    for i in range(0,255):
        res = connect("192.168.1."+str(i), 22)
        if res:
            print("Device found at: ", "192.168.1."+str(i) + ":"+str(22))
    

提交回复
热议问题