eth.go (1231B)
1 package eth 2 3 import ( 4 "context" 5 "fmt" 6 "net" 7 ) 8 9 type Config struct { 10 Iface string `json:"iface"` 11 } 12 13 type Block struct { 14 iface string 15 } 16 17 func New(iface string) *Block { 18 return &Block{iface: iface} 19 } 20 21 func (b *Block) Name() string { 22 return "eth" 23 } 24 25 func (b *Block) Render(ctx context.Context) (string, error) { 26 iface, err := net.InterfaceByName(b.iface) 27 if err != nil { 28 if err.Error() == "route ip+net: no such network interface" { 29 return " ", nil 30 } 31 return "", fmt.Errorf( 32 "failed to get interface %s: %v", b.iface, err, 33 ) 34 } 35 36 var ip4, ip6 string 37 addrs, err := iface.Addrs() 38 if err != nil { 39 return "", fmt.Errorf("failed to get addresses: %v", err) 40 } 41 42 for _, addr := range addrs { 43 a := addr.String() 44 if isIPv4(a) { 45 ip4 = a 46 continue 47 } else { 48 ip6 = a 49 } 50 } 51 52 switch { 53 case ip4 == "" && ip6 == "": 54 return " ", nil 55 case ip4 != "" && ip6 == "": 56 return fmt.Sprintf(" %s", ip4), nil 57 case ip4 == "" && ip6 != "": 58 return fmt.Sprintf(" %s", ip6), nil 59 default: 60 return fmt.Sprintf(" %s %s", ip4, ip6), nil 61 } 62 } 63 64 func isIPv4(s string) bool { 65 for i := 0; i < len(s); i++ { 66 switch s[i] { 67 case '.': 68 return true 69 case ':': 70 return false 71 } 72 } 73 74 return false 75 }