2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Go言語でWake On Lanパケットを送信する

Posted at

# はじめに

ネットワークにマジックパッケットを送信してPCの電源をONにする技術Wake On Lan

のマジックパケットをGo言語から送信する話です。

Wake on LANパケットを送信するプログラム

package main

import (
	"log"
	"net"
)

func main() {
	err := SendWakeOnLanPacket("78:84:3c:2a:ac:08")
	if err != nil {
		log.Fatalln(err)
	}

}

// SendWakeOnLanPacket : send wake on lan magic packet to mac address
func SendWakeOnLanPacket(mac string) error {
	ra, err := net.ResolveUDPAddr("udp4", "255.255.255.255:9")
	if err != nil {
		return err
	}
	la, err := net.ResolveUDPAddr("udp4", ":0")
	if err != nil {
		return err
	}
	c, err := net.DialUDP("udp4", la, ra)
	if err != nil {
		return err
	}
	defer c.Close()
	hw, err := net.ParseMAC(mac)
	if err != nil {
		return err
	}
	packet := []byte{}
	prefix := []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
	packet = append(packet, prefix...)
	for i := 0; i < 16; i++ {
		packet = append(packet, hw...)
	}
	_, err = c.Write(packet)
	return err
}

ポイントは

UDPの破棄ポート(9)へブロードキャストで送信する

ra, err := net.ResolveUDPAddr("udp4", "255.255.255.255:9")
	if err != nil {
		return err
	}
	la, err := net.ResolveUDPAddr("udp4", ":0")
	if err != nil {
		return err
	}
	c, err := net.DialUDP("udp4", la, ra)
	if err != nil {
		return err
	}
	defer c.Close()

文字列のMACアドレスをバイナリーにする

hw, err := net.ParseMAC(mac)
	if err != nil {
		return err
	}

マジックパケットの作成

packet := []byte{}
	prefix := []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
	packet = append(packet, prefix...)
	for i := 0; i < 16; i++ {
		packet = append(packet, hw...)
	}
	_, err = c.Write(packet)

送信結果

パケットキャプチャーすると

image.png

余談

この機能は旧版TWSNMPのユーザーからの要望に対応してTWSNMP FC/FKをWake On Lan対応した時に作ったものです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?