mirror of
https://gitee.com/shikong-sk/gofiber-study
synced 2025-02-23 15:22:14 +08:00
wol/service
This commit is contained in:
parent
6184e52b01
commit
6662b67ca5
@ -1,5 +1,19 @@
|
||||
package wol
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
MacFormatError = errors.New("mac 地址格式错误")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
}
|
||||
|
||||
@ -9,6 +23,65 @@ func InitService() {
|
||||
Services = &Service{}
|
||||
}
|
||||
|
||||
func WakeUp(mac string, port int) {
|
||||
func (s *Service) validateMac(mac string) bool {
|
||||
exp, _ := regexp.Compile("([0-9a-fA-F]{2}(-|:)?){5}([a-fA-F0-9]{2})")
|
||||
|
||||
macLen := len(mac)
|
||||
|
||||
return exp.MatchString(mac) && (macLen == 12 || macLen == 17)
|
||||
}
|
||||
|
||||
func (s *Service) WakeUp(mac string, port int) error {
|
||||
mac = strings.Replace(strings.Replace(mac, ":", "", -1), "-", "", -1)
|
||||
if !s.validateMac(mac) {
|
||||
return MacFormatError
|
||||
}
|
||||
|
||||
return s.wake(mac, port)
|
||||
}
|
||||
|
||||
func (s *Service) wake(mac string, port int) error {
|
||||
udpAddr, _ := net.ResolveUDPAddr("udp", fmt.Sprintf("255.255.255.255:%d", port))
|
||||
interfaces, err := net.Interfaces()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
macHex, _ := hex.DecodeString(mac)
|
||||
// 广播MAC地址 FF:FF:FF:FF:FF:FF
|
||||
var broadcast = []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
|
||||
var buffer bytes.Buffer
|
||||
buffer.Write(broadcast)
|
||||
for i := 0; i < 16; i++ {
|
||||
buffer.Write(macHex)
|
||||
}
|
||||
wolPackage := buffer.Bytes()
|
||||
|
||||
for _, i := range interfaces {
|
||||
if i.Flags&net.FlagUp == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
addrs, err := i.Addrs()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, addr := range addrs {
|
||||
if ip, ok := addr.(*net.IPNet); ok {
|
||||
if ipv4 := ip.IP.To4(); ipv4 != nil {
|
||||
conn, err := net.DialUDP("udp", &net.UDPAddr{IP: ipv4}, udpAddr)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = conn.Write(wolPackage)
|
||||
_ = conn.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
@ -81,3 +81,12 @@ func TestWol(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWOLService(t *testing.T) {
|
||||
var service *Service
|
||||
err := service.WakeUp("00-E0-4C-84-50-EB", 9)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log("wol 唤醒成功")
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user