pretty-ip/main.go

86 lines
2.1 KiB
Go

package main
import (
"fmt"
"net"
"github.com/charmbracelet/lipgloss"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
)
func main() {
// Styles
headerStyle := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("63"))
ipStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("203"))
upStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("42"))
downStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("196"))
addrStyle := lipgloss.NewStyle().Faint(true)
infoStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("33"))
// Get all links
links, err := netlink.LinkList()
if err != nil {
fmt.Println("Error listing links:", err)
return
}
for _, link := range links {
attrs := link.Attrs()
if attrs == nil {
continue
}
// Link state
state := downStyle.Render("DOWN")
if attrs.Flags&net.FlagUp != 0 {
state = upStyle.Render("UP")
}
// Interface header
fmt.Print(headerStyle.Render(attrs.Name), " ")
fmt.Printf(addrStyle.Render(" %s"), attrs.HardwareAddr)
fmt.Printf(addrStyle.Render(" %d"), attrs.MTU)
fmt.Printf(" %s\n", state)
// IPv4 addresses
addrs, err := netlink.AddrList(link, unix.AF_INET)
if err != nil {
fmt.Println(" Error getting addresses:", err)
continue
}
for _, addr := range addrs {
fmt.Println(" ", ipStyle.Render(addr.IPNet.String()))
}
// Veth handling
if link.Type() == "veth" {
fmt.Println(" ", infoStyle.Render("Veth interface"))
// Try to find peer by looking for other veths with same parent or hint from name
// No peer name is available here, so we must guess
// We'll mention that if no matching veth exists, it's likely in another netns
peerFound := false
for _, other := range links {
if other.Attrs().Index == attrs.Index {
continue
}
if other.Type() == "veth" && other.Attrs().ParentIndex == attrs.Index {
fmt.Println(" ", infoStyle.Render("Likely peer:"), other.Attrs().Name)
peerFound = true
break
}
}
if !peerFound {
fmt.Println(" ", infoStyle.Render("Peer likely in another namespace"))
}
}
fmt.Println()
}
}