src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

eth.go (1204B)


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