github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/system/net/net.go (about)

     1  package net
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"github.com/isyscore/isc-gobase/system/common"
     7  	"net"
     8  	"time"
     9  )
    10  
    11  var invoke common.Invoker = common.Invoke{}
    12  
    13  type IOCountersStat struct {
    14  	Name        string `json:"name"`        // interface name
    15  	BytesSent   uint64 `json:"bytesSent"`   // number of bytes sent
    16  	BytesRecv   uint64 `json:"bytesRecv"`   // number of bytes received
    17  	PacketsSent uint64 `json:"packetsSent"` // number of packets sent
    18  	PacketsRecv uint64 `json:"packetsRecv"` // number of packets received
    19  	Errin       uint64 `json:"errin"`       // total number of errors while receiving
    20  	Errout      uint64 `json:"errout"`      // total number of errors while sending
    21  	Dropin      uint64 `json:"dropin"`      // total number of incoming packets which were dropped
    22  	Dropout     uint64 `json:"dropout"`     // total number of outgoing packets which were dropped (always 0 on OSX and BSD)
    23  	Fifoin      uint64 `json:"fifoin"`      // total number of FIFO buffers errors while receiving
    24  	Fifoout     uint64 `json:"fifoout"`     // total number of FIFO buffers errors while sending
    25  
    26  }
    27  
    28  // Addr is implemented compatibility to psutil
    29  type Addr struct {
    30  	IP   string `json:"ip"`
    31  	Port uint32 `json:"port"`
    32  }
    33  
    34  type ConnectionStat struct {
    35  	Fd     uint32  `json:"fd"`
    36  	Family uint32  `json:"family"`
    37  	Type   uint32  `json:"type"`
    38  	Laddr  Addr    `json:"localaddr"`
    39  	Raddr  Addr    `json:"remoteaddr"`
    40  	Status string  `json:"status"`
    41  	Uids   []int32 `json:"uids"`
    42  	Pid    int32   `json:"pid"`
    43  }
    44  
    45  // ProtoCountersStat System-wide stats about different network protocols
    46  type ProtoCountersStat struct {
    47  	Protocol string           `json:"protocol"`
    48  	Stats    map[string]int64 `json:"stats"`
    49  }
    50  
    51  // InterfaceAddr NetInterfaceAddr is designed for represent interface addresses
    52  type InterfaceAddr struct {
    53  	Addr string `json:"addr"`
    54  }
    55  
    56  type InterfaceStat struct {
    57  	Index        int             `json:"index"`
    58  	MTU          int             `json:"mtu"`          // maximum transmission unit
    59  	Name         string          `json:"name"`         // e.g., "en0", "lo0", "eth0.100"
    60  	HardwareAddr string          `json:"hardwareaddr"` // IEEE MAC-48, EUI-48 and EUI-64 form
    61  	Flags        []string        `json:"flags"`        // e.g., FlagUp, FlagLoopback, FlagMulticast
    62  	Addrs        []InterfaceAddr `json:"addrs"`
    63  }
    64  
    65  type FilterStat struct {
    66  	ConnTrackCount int64 `json:"conntrackCount"`
    67  	ConnTrackMax   int64 `json:"conntrackMax"`
    68  }
    69  
    70  // ConntrackStat has conntrack summary info
    71  type ConntrackStat struct {
    72  	Entries       uint32 `json:"entries"`        // Number of entries in the conntrack table
    73  	Searched      uint32 `json:"searched"`       // Number of conntrack table lookups performed
    74  	Found         uint32 `json:"found"`          // Number of searched entries which were successful
    75  	New           uint32 `json:"new"`            // Number of entries added which were not expected before
    76  	Invalid       uint32 `json:"invalid"`        // Number of packets seen which can not be tracked
    77  	Ignore        uint32 `json:"ignore"`         // Packets seen which are already connected to an entry
    78  	Delete        uint32 `json:"delete"`         // Number of entries which were removed
    79  	DeleteList    uint32 `json:"delete_list"`    // Number of entries which were put to dying list
    80  	Insert        uint32 `json:"insert"`         // Number of entries inserted into the list
    81  	InsertFailed  uint32 `json:"insert_failed"`  // # insertion attempted but failed (same entry exists)
    82  	Drop          uint32 `json:"drop"`           // Number of packets dropped due to conntrack failure.
    83  	EarlyDrop     uint32 `json:"early_drop"`     // Dropped entries to make room for new ones, if maxsize reached
    84  	IcmpError     uint32 `json:"icmp_error"`     // Subset of invalid. Packets that can't be tracked d/t error
    85  	ExpectNew     uint32 `json:"expect_new"`     // Entries added after an expectation was already present
    86  	ExpectCreate  uint32 `json:"expect_create"`  // Expectations added
    87  	ExpectDelete  uint32 `json:"expect_delete"`  // Expectations deleted
    88  	SearchRestart uint32 `json:"search_restart"` // Conntrack table lookups restarted due to hashtable resizes
    89  }
    90  
    91  func NewConntrackStat(e uint32, s uint32, f uint32, n uint32, inv uint32, ign uint32, del uint32, dlst uint32, ins uint32, insfail uint32, drop uint32, edrop uint32, ie uint32, en uint32, ec uint32, ed uint32, sr uint32) *ConntrackStat {
    92  	return &ConntrackStat{
    93  		Entries:       e,
    94  		Searched:      s,
    95  		Found:         f,
    96  		New:           n,
    97  		Invalid:       inv,
    98  		Ignore:        ign,
    99  		Delete:        del,
   100  		DeleteList:    dlst,
   101  		Insert:        ins,
   102  		InsertFailed:  insfail,
   103  		Drop:          drop,
   104  		EarlyDrop:     edrop,
   105  		IcmpError:     ie,
   106  		ExpectNew:     en,
   107  		ExpectCreate:  ec,
   108  		ExpectDelete:  ed,
   109  		SearchRestart: sr,
   110  	}
   111  }
   112  
   113  type ConntrackStatList struct {
   114  	items []*ConntrackStat
   115  }
   116  
   117  func NewConntrackStatList() *ConntrackStatList {
   118  	return &ConntrackStatList{
   119  		items: []*ConntrackStat{},
   120  	}
   121  }
   122  
   123  func (l *ConntrackStatList) Append(c *ConntrackStat) {
   124  	l.items = append(l.items, c)
   125  }
   126  
   127  func (l *ConntrackStatList) Items() []ConntrackStat {
   128  	items := make([]ConntrackStat, len(l.items), len(l.items))
   129  	for i, el := range l.items {
   130  		items[i] = *el
   131  	}
   132  	return items
   133  }
   134  
   135  // Summary returns a single-element list with totals from all list items.
   136  func (l *ConntrackStatList) Summary() []ConntrackStat {
   137  	summary := NewConntrackStat(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
   138  	for _, cs := range l.items {
   139  		summary.Entries += cs.Entries
   140  		summary.Searched += cs.Searched
   141  		summary.Found += cs.Found
   142  		summary.New += cs.New
   143  		summary.Invalid += cs.Invalid
   144  		summary.Ignore += cs.Ignore
   145  		summary.Delete += cs.Delete
   146  		summary.DeleteList += cs.DeleteList
   147  		summary.Insert += cs.Insert
   148  		summary.InsertFailed += cs.InsertFailed
   149  		summary.Drop += cs.Drop
   150  		summary.EarlyDrop += cs.EarlyDrop
   151  		summary.IcmpError += cs.IcmpError
   152  		summary.ExpectNew += cs.ExpectNew
   153  		summary.ExpectCreate += cs.ExpectCreate
   154  		summary.ExpectDelete += cs.ExpectDelete
   155  		summary.SearchRestart += cs.SearchRestart
   156  	}
   157  	return []ConntrackStat{*summary}
   158  }
   159  
   160  func (n IOCountersStat) String() string {
   161  	s, _ := json.Marshal(n)
   162  	return string(s)
   163  }
   164  
   165  func (n ConnectionStat) String() string {
   166  	s, _ := json.Marshal(n)
   167  	return string(s)
   168  }
   169  
   170  func (n ProtoCountersStat) String() string {
   171  	s, _ := json.Marshal(n)
   172  	return string(s)
   173  }
   174  
   175  func (a Addr) String() string {
   176  	s, _ := json.Marshal(a)
   177  	return string(s)
   178  }
   179  
   180  func (n InterfaceStat) String() string {
   181  	s, _ := json.Marshal(n)
   182  	return string(s)
   183  }
   184  
   185  func (n InterfaceAddr) String() string {
   186  	s, _ := json.Marshal(n)
   187  	return string(s)
   188  }
   189  
   190  func (n ConntrackStat) String() string {
   191  	s, _ := json.Marshal(n)
   192  	return string(s)
   193  }
   194  
   195  func Interfaces() ([]InterfaceStat, error) {
   196  	return InterfacesWithContext(context.Background())
   197  }
   198  
   199  func InterfacesWithContext(ctx context.Context) ([]InterfaceStat, error) {
   200  	is, err := net.Interfaces()
   201  	if err != nil {
   202  		return nil, err
   203  	}
   204  	ret := make([]InterfaceStat, 0, len(is))
   205  	for _, ifi := range is {
   206  
   207  		var flags []string
   208  		if ifi.Flags&net.FlagUp != 0 {
   209  			flags = append(flags, "up")
   210  		}
   211  		if ifi.Flags&net.FlagBroadcast != 0 {
   212  			flags = append(flags, "broadcast")
   213  		}
   214  		if ifi.Flags&net.FlagLoopback != 0 {
   215  			flags = append(flags, "loopback")
   216  		}
   217  		if ifi.Flags&net.FlagPointToPoint != 0 {
   218  			flags = append(flags, "pointtopoint")
   219  		}
   220  		if ifi.Flags&net.FlagMulticast != 0 {
   221  			flags = append(flags, "multicast")
   222  		}
   223  
   224  		r := InterfaceStat{
   225  			Index:        ifi.Index,
   226  			Name:         ifi.Name,
   227  			MTU:          ifi.MTU,
   228  			HardwareAddr: ifi.HardwareAddr.String(),
   229  			Flags:        flags,
   230  		}
   231  		addrs, err := ifi.Addrs()
   232  		if err == nil {
   233  			r.Addrs = make([]InterfaceAddr, 0, len(addrs))
   234  			for _, addr := range addrs {
   235  				r.Addrs = append(r.Addrs, InterfaceAddr{
   236  					Addr: addr.String(),
   237  				})
   238  			}
   239  
   240  		}
   241  		ret = append(ret, r)
   242  	}
   243  
   244  	return ret, nil
   245  }
   246  
   247  func getIOCountersAll(n []IOCountersStat) ([]IOCountersStat, error) {
   248  	r := IOCountersStat{
   249  		Name: "all",
   250  	}
   251  	for _, nic := range n {
   252  		r.BytesRecv += nic.BytesRecv
   253  		r.PacketsRecv += nic.PacketsRecv
   254  		r.Errin += nic.Errin
   255  		r.Dropin += nic.Dropin
   256  		r.BytesSent += nic.BytesSent
   257  		r.PacketsSent += nic.PacketsSent
   258  		r.Errout += nic.Errout
   259  		r.Dropout += nic.Dropout
   260  	}
   261  
   262  	return []IOCountersStat{r}, nil
   263  }
   264  
   265  // 判断网络是否可达
   266  // ipAndPort:格式:{ip}:{port}
   267  func IpPortAvailable(ipAndPort string) bool {
   268  	conn, err := net.DialTimeout("tcp", ipAndPort, 2 * time.Second)
   269  	if err != nil {
   270  		return false
   271  	} else {
   272  		if conn != nil {
   273  			err := conn.Close()
   274  			if err != nil {
   275  				return false
   276  			}
   277  			return true
   278  		} else {
   279  			return false
   280  		}
   281  	}
   282  }