0
0

More than 1 year has passed since last update.

Go でホストのプライマリ IP アドレスを取得する (Linux)

Posted at

github.com/google/gopacket/routing パッケージを使う.
インターネット上のホストへの経路とソース IP アドレスを取得することができる.

Linux しか対応していない模様

main.go
package main

import (
	"fmt"
	"net"

	"github.com/google/gopacket/routing"
)

func main() {
	router, _ := routing.New()
	internetHost := net.IP{8, 8, 8, 8}
	_, _, primaryIp, _ := router.Route(internetHost)

	fmt.Printf("ip = %v\n", primaryIp)
}

out of order iface... のエラーが出る時

Docker などの環境では,以下のようなエラーが出る場合がある.

out of order iface X = {14 1500 ethX XX:XX:XX:XX:XX:XX up|broadcast|multicast}

これは routingバグ のようで,修正の PR が Close されていて放置されている.  
Workaround として, Close された PR のコードを使わせてもらうことができる.

go.mod
//require github.com/google/gopacket v1.1.19
// 以下に変更
require github.com/google/gopacket v1.1.20-0.20210429153827-3eaba0894325
0
0
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
0
0