本机IP地址查看及获取,包括IPV6
本帖最后由 lgk 于 2024-11-13 19:44 编辑自己借助于编程代码助手,用python写的一个获取本机IP地址的小程序,单文件,双击即可复制IP地址,不知道代码结构是否足够清晰,还请大佬们批评指正{:1_893:}
import tkinter as tk
from tkinter import ttk
import socket
import psutil
import pyperclip
import subprocess
from tkinter import messagebox
def get_network_info():
"""获取网络接口信息"""
network_info = []
addrs = psutil.net_if_addrs()
net_stats = psutil.net_if_stats()
seen_interfaces = set()
for interface in addrs.keys():
if net_stats.isup and interface not in seen_interfaces:
ipv4_address, mac_address = "Not Available", "Not Available"
ipv6_addresses = []
for addr in addrs:
if addr.family == socket.AF_INET:
ipv4_address = addr.address
elif addr.family == socket.AF_INET6:
if addr.address.startswith("fe80"):
ipv6_addresses.append(f"{addr.address} (内网可用)")
else:
ipv6_addresses.append(addr.address)
elif addr.family == psutil.AF_LINK:
mac_address = addr.address
# 将收集到的信息添加到列表中
for ipv6_addr in ipv6_addresses:
network_info.append()
seen_interfaces.add(interface)
return network_info
def copy_selected_value(tree, item_id, column):
"""复制选中的值并弹出提示框"""
value = tree.item(item_id, 'values').index(column)]
if column == "IPv6":
value = value.split(" (")# 去掉备注
pyperclip.copy(value)
messagebox.showinfo("提示", f"{column} '{value}' 复制成功!")
def ping_ip(ip_address):
"""在新CMD窗口中对指定IP进行ping操作"""
try:
subprocess.Popen(f"start cmd /k ping {ip_address}", shell=True)
except Exception as e:
messagebox.showerror("错误", f"无法 ping IP 地址: {e}")
def show_context_menu(event, tree):
"""显示右键上下文菜单"""
selected_item = tree.selection()
if selected_item:
column_index = int(tree.identify_column(event.x).replace("#", "")) - 1
ip_address = tree.item(selected_item, 'values')
context_menu = tk.Menu(root, tearoff=0)
context_menu.add_command(label="Ping", command=lambda: ping_ip(ip_address))
context_menu.post(event.x_root, event.y_root)
def on_tree_item_double_click(event, tree):
"""处理双击事件以复制值"""
selected_item = tree.selection()
column = tree.identify_column(event.x)
column_index = int(column.replace("#", "")) - 1
copy_selected_value(tree, selected_item, tree['columns'])
def setup_treeview(frame):
"""设置树形视图及其样式"""
columns = ("网络接口名称", "IPv4", "IPv6", "MAC")
tree = ttk.Treeview(frame, columns=columns, show="headings")
# 设置列标题和宽度
for col in columns:
tree.heading(col, text=col)
tree.column(col, width=200 if col == "网络接口名称" else 300, anchor='center')
style = ttk.Style()
style.configure("Treeview", rowheight=25, fieldbackground="white", borderwidth=2, relief="solid")
style.configure("Treeview.Heading", font=('Helvetica', 12, 'bold'), borderwidth=2, relief="solid")
return tree
def show_network_info():
global root# 将root设置为全局变量
root = tk.Tk()
root.title("IP 地址查看器(双击复制)")
frame = ttk.Frame(root)
frame.pack(fill=tk.BOTH, expand=True)
network_info = get_network_info()
interface_tree = setup_treeview(frame)
for info in network_info:
interface_tree.insert("", tk.END, values=info)
# 绑定事件
interface_tree.bind("<Double-1>", lambda event: on_tree_item_double_click(event, interface_tree))
interface_tree.bind("<Button-3>", lambda event: show_context_menu(event, interface_tree))
scrollbar = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=interface_tree.yview)
interface_tree.configure(yscrollcommand=scrollbar.set)
interface_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 调整窗口大小以适应内容
root.update_idletasks()
row_count = len(network_info)
root.minsize(root.winfo_width(), 25 * row_count + 100)
root.geometry("")# 根据内容动态调整窗口大小
root.mainloop()
if __name__ == "__main__":
show_network_info()
蓝奏云网盘(永久有效):https://lgkl.lanzout.com/i3yOp2ez2kdc
密码:2prj
ping_ip 函数未区分 IPv4 和 IPv6,建议添加自动识别:
def ping_ip(ip_address):
cmd = "ping" if ":" not in ip_address else "ping -6"
try:
subprocess.Popen(f"start cmd /k {cmd} {ip_address}", shell=True)
except Exception as e:
messagebox.showerror("错误", f"无法 ping IP 地址: {e}") xc4447 发表于 2024-11-13 22:15
这个跟命令行的那个获取内容是一样的吗。一些比较特殊的网桥(比如基于hyperv的wsl和wsa)可以获取到吗
跟命令行获取到的是一样的,虚拟网卡应该也是能够获取的,基于Hyper-V的没有测试过,不过VMware的都能获取到,大佬可以自行测试一下{:1_893:} 虽然用命令行也可以 挺不错的,很棒 cmd也方便呀 感谢分享,这是很实用的工具 非常棒的软件,请问是window还是linux系统适用呢? 这个跟命令行的那个获取内容是一样的吗。一些比较特殊的网桥(比如基于hyperv的wsl和wsa)可以获取到吗 这不就是一个命令的事儿????? 体验一下,非常有效,如果再带上子网掩码、网关以及DNS就更好了
ipconfig /all也能看