-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
126 lines (113 loc) · 2.22 KB
/
Copy pathmain.go
File metadata and controls
126 lines (113 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"bytes"
"encoding/hex"
"errors"
"log"
"net"
"net/http"
"strings"
)
func main(){
http.HandleFunc("/wol", handleHttp)
er := http.ListenAndServe(":2333", nil)
if er != nil{
log.Fatal(er)
}
}
func makeOnLan(mac, nic string) error{
hw := strings.Replace(strings.Replace(mac, ":", "", -1), "-", "", -1)
if len(hw) != 12 {
return errors.New("hw != 12")
}
macHex, er := hex.DecodeString(hw)
if er != nil {
return er
}
var bcast = []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
var buf bytes.Buffer
buf.Write(bcast)
for i := 0; i < 16; i++ {
buf.Write(macHex)
}
mp := buf.Bytes()
if len(mp) != 102 {
return errors.New("mp != 102")
}
send := net.UDPAddr{}
if len(nic) != 0 {
inter, err := net.InterfaceByName(nic)
if err != nil {
return err
}
if (inter.Flags & net.FlagUp) == 0 {
return errors.New("网卡未工作")
}
addrs, err := inter.Addrs()
if err != nil {
return err
}
isOK := false
for _, addr := range addrs {
if ip, ok := addr.(*net.IPNet); ok {
if ipv4 := ip.IP.To4(); ipv4 != nil {
isOK = true
send.IP = ipv4
break
}
}
}
if !isOK {
return errors.New("未找到网卡所绑定的ip")
}
target := net.UDPAddr{IP: net.IPv4bcast}
conn, er := net.DialUDP("udp", &send, &target)
if er != nil {
return er
}
defer conn.Close()
_, err = conn.Write(mp)
if err != nil {
return errors.New("发送失败:" + err.Error())
} else {
return nil
}
}
return errors.New("nic == 0")
}
func handleHttp(w http.ResponseWriter, re *http.Request){
er := re.ParseForm()
if er != nil{
_, wer := w.Write([]byte("参数处理失败"))
if wer != nil{
log.Println("消息发送失败")
}
return
}
mac := re.Form.Get("mac")
if mac == ""{
_, wer := w.Write([]byte("无法寻找到mac参数"))
if wer != nil{
log.Println("发送失败")
}
return
}
nic := re.Form.Get("nic")
var mer error
if nic == ""{
mer = makeOnLan(mac, "wlx048d38d361ec")
}else{
mer = makeOnLan(mac, nic)
}
if mer != nil{
_, wer := w.Write([]byte(mer.Error()))
if wer != nil{
log.Println("发送失败")
}
}else{
_, wer := w.Write([]byte("已发送唤醒指令"))
if wer != nil{
log.Println("发送失败")
}
}
}