Browse Source

添加机器码

sugar 3 năm trước cách đây
mục cha
commit
6d0daf3d0f
3 tập tin đã thay đổi với 61 bổ sung5 xóa
  1. 15 0
      .vscode/launch.json
  2. 4 0
      options_test.go
  3. 42 5
      reporter.go

+ 15 - 0
.vscode/launch.json

@@ -0,0 +1,15 @@
+{
+  // Use IntelliSense to learn about possible attributes.
+  // Hover to view descriptions of existing attributes.
+  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+  "version": "0.2.0",
+  "configurations": [
+    {
+      "name": "Launch Package",
+      "type": "go",
+      "request": "launch",
+      "mode": "auto",
+      "program": "${fileDirname}/cmd/main"
+    }
+  ]
+}

+ 4 - 0
options_test.go

@@ -20,3 +20,7 @@ func TestOptions_ShortName(t *testing.T) {
 		})
 	}
 }
+
+func TestMachineCode(t *testing.T) {
+	defaultReporter.Do("test")
+}

+ 42 - 5
reporter.go

@@ -1,7 +1,9 @@
 package micro
 
 import (
+	"crypto/md5"
 	"encoding/binary"
+	"hash"
 	"net"
 	"runtime"
 )
@@ -24,7 +26,8 @@ const (
 
 type (
 	Reporter struct {
-		ServerAddr string
+		ServerAddr  string
+		machineCode []byte
 	}
 
 	reporterPayload struct {
@@ -35,6 +38,28 @@ type (
 	}
 )
 
+func (r *Reporter) getMachineCode() []byte {
+	var (
+		b       []byte
+		err     error
+		encoder hash.Hash
+		inters  []net.Interface
+	)
+	//get network hard addr
+	if inters, err = net.Interfaces(); err == nil {
+		for _, inter := range inters {
+			if inter.HardwareAddr != nil {
+				b = inter.HardwareAddr
+				break
+			}
+		}
+	}
+	b = append(b, byte(runtime.NumCPU()))
+	encoder = md5.New()
+	encoder.Write(b)
+	return encoder.Sum(nil)
+}
+
 func (r *Reporter) Collect() (payload *reporterPayload) {
 	var mem runtime.MemStats
 	payload = &reporterPayload{
@@ -52,16 +77,25 @@ func (r *Reporter) Collect() (payload *reporterPayload) {
 		payload.OS = OsOther
 	}
 	runtime.ReadMemStats(&mem)
-	payload.Memory = uint16(mem.Alloc / 1024 / 1024) //MB
+	payload.Memory = uint16(mem.Alloc / 1024) //KB
 	return
 }
 
 func (r *Reporter) Marshal(payload *reporterPayload) (buf []byte) {
-	buf = make([]byte, 4+len(payload.Data))
+	var (
+		dl uint8
+		cl uint8
+	)
+	dl = uint8(len(payload.Data))
+	cl = uint8(len(r.machineCode))
+	buf = make([]byte, 6+int(dl)+int(cl))
 	buf[0] = payload.OS
 	buf[1] = payload.Cpus
-	binary.BigEndian.PutUint16(buf[2:4], payload.Memory)
-	copy(buf[4:], payload.Data[:])
+	buf[2] = cl
+	buf[3] = dl
+	binary.BigEndian.PutUint16(buf[4:6], payload.Memory)
+	copy(buf[6:6+cl], r.machineCode)
+	copy(buf[6+cl:], payload.Data[:])
 	for i, c := range buf {
 		buf[i] = c ^ 0x1F
 	}
@@ -74,6 +108,9 @@ func (r *Reporter) Do(data string) (err error) {
 		udpAddr *net.UDPAddr
 		payload *reporterPayload
 	)
+	if r.machineCode == nil {
+		r.machineCode = r.getMachineCode()
+	}
 	if udpAddr, err = net.ResolveUDPAddr("udp", r.ServerAddr); err != nil {
 		return
 	}