简体   繁体   中英

Is there a method in python for accessing the IP addresses of named “Network Connections” in Windows? Ex: “Ethernet” or “Local Area Connection”

I just started using Python the other day so forgive me if this is a dumb question. I am creating a small functional windows application via Tkinter that will allow myself and my coworkers to quickly change our IP addresses with the click of a button. This feature already works, however, I want to create a label in my window that displays the computer's Ethernet IP address upon opening the application and upon clicking a button to change the IP to show that it actually worked. I found a library called "Ifaddr" that I thought would work, but instead of displaying the connection name like "Ethernet" or "Local Area Connection" it displays the adapter name like "Realtek PCIe 2.5GbE Family Controller". The only problem with this is that not all of my coworkers have laptops with a Realtek Controller some are Intel or what have you. Any solutions would be very appreciated.

Thanks to @acw1668 for your comment, but I think I may have found an even better solution than what those answers suggest. I found this article https://janakiev.com/blog/python-shell-commands/ and after reading I tried using the os.popen command and it worked just fine, and the best part is you can use the standard library to achieve what I wanted. Here is an example:

import os
ethernetset1=os.popen("netsh interface ip show addresses Ethernet").read().split('\n')
print (ethernetset1)

Which results in:

['', 'Configuration for interface "Ethernet"', '    DHCP enabled:                         No', '    IP Address:                           10.74.126.120', '    Subnet Prefix:                        10.74.124.0/22 (mask 255.255.252.0)', '    Default Gateway:                      0.0.0.0', '    Gateway Metric:                       1', '    InterfaceMetric:                      35', '', '']

This is great in my opinion because you can print all the details about a connection name and even access the list elements to get what you want(IP, Gateway, Mask). Is this the most ideal way to do this? I can't answer that as I'm new to programming in general. Hopefully this will help someone in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM