golang 远程唤醒开机实例

package main

import (
   "fmt"
   "github.com/sabhiram/go-wol"
   "io"
   "log"
   "net"
   "net/http"
   "time"
)

func main() {
   http.HandleFunc("/makeUp", func(w http.ResponseWriter, r *http.Request) {
      macAddr := r.FormValue("mac")
      ip := r.FormValue("ip")
      secret := r.FormValue("secret")
      if secret != "407787759" {
         io.WriteString(w, "

非常操作!

") return } if ip != "" { b := isping(ip) if b { io.WriteString(w, "

已开机!

") return } } log.Println(macAddr, ip, secret) wakeUp(macAddr) io.WriteString(w, "

开机指令发送成功!请稍候...

") }) http.ListenAndServe(":2019", nil) } func wakeUp(macAddr string) { var localAddr *net.UDPAddr localAddr, _ = ipFromInterface("eno5") udpAddr, err := net.ResolveUDPAddr("udp", "255.255.255.255:9") if err != nil { panic(err) } mp, err := wol.New(macAddr) if err != nil { panic(err) } bs, err := mp.Marshal() if err != nil { panic(err) } conn, err := net.DialUDP("udp", localAddr, udpAddr) if err != nil { panic(err) } defer conn.Close() n, err := conn.Write(bs) if err == nil && n != 102 { err = fmt.Errorf("magic packet sent was %d bytes (expected 102 bytes sent)", n) } fmt.Printf("Magic packet sent successfully to %s\n", macAddr) } // ipFromInterface returns a `*net.UDPAddr` from a network interface name. func ipFromInterface(iface string) (*net.UDPAddr, error) { ief, err := net.InterfaceByName(iface) if err != nil { return nil, err } addrs, err := ief.Addrs() if err == nil && len(addrs) <= 0 { err = fmt.Errorf("no address associated with interface %s", iface) } if err != nil { return nil, err } // Validate that one of the addrs is a valid network IP address. for _, addr := range addrs { switch ip := addr.(type) { case *net.IPNet: // Verify that the DefaultMask for the address we want to use exists. if ip.IP.DefaultMask() != nil { return &net.UDPAddr{ IP: ip.IP, }, nil } } } return nil, fmt.Errorf("no address associated with interface %s", iface) } func isping(ip string) bool { recvBuf1 := make([]byte, 2048) payload := []byte{0x08, 0x00, 0x4d, 0x4b, 0x00, 0x01, 0x00, 0x10, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69} Time, _ := time.ParseDuration("1s") conn, err := net.DialTimeout("ip4:icmp", ip, Time) if err != nil { fmt.Println("bibi") return false } _, err = conn.Write(payload) if err != nil { return false } conn.SetReadDeadline(time.Now().Add(time.Second * 2)) num, err := conn.Read(recvBuf1[0:]) conn.SetReadDeadline(time.Time{}) if string(recvBuf1[0:num]) != "" { return true } return false }

通过web访问程序,让它发出魔术包唤醒同网段的其它PC

要远程开机的PC要设置网卡唤醒功能!

然后通过http://您的程序运行的IP:2019/makeUp?secret=407787759&mac=00:00:59:96:CC:0c(你要开机的MAC地址)

转载于:https://my.oschina.net/wgc2010/blog/2961109

你可能感兴趣的:(golang 远程唤醒开机实例)