Finding local IP addresses using Python's stdlib

后端 未结 30 2593
北恋
北恋 2020-11-21 23:54

How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?

30条回答
  •  广开言路
    2020-11-22 00:29

    Well you can use the command "ip route" on GNU/Linux to know your current IP address.

    This shows the IP given to the interface by the DHCP server running on the router/modem. Usually "192.168.1.1/24" is the IP for local network where "24" means the range of posible IP addresses given by the DHCP server within the mask range.

    Here's an example: Note that PyNotify is just an addition to get my point straight and is not required at all

    #! /usr/bin/env python
    
    import sys , pynotify
    
    if sys.version_info[1] != 7:
       raise RuntimeError('Python 2.7 And Above Only')       
    
    from subprocess import check_output # Available on Python 2.7+ | N/A 
    
    IP = check_output(['ip', 'route'])
    Split_Result = IP.split()
    
    # print Split_Result[2] # Remove "#" to enable
    
    pynotify.init("image")
    notify = pynotify.Notification("Ip", "Server Running At:" + Split_Result[2] , "/home/User/wireless.png")    
    notify.show()    
    

    The advantage of this is that you don't need to specify the network interface. That's pretty useful when running a socket server

    You can install PyNotify using easy_install or even Pip:

    easy_install py-notify
    

    or

    pip install py-notify
    

    or within python script/interpreter

    from pip import main
    
    main(['install', 'py-notify'])
    

提交回复
热议问题