LoginSignup
7
6

More than 3 years have passed since last update.

GoでSTUNサーバを使って自分のパブリックIPアドレスを取得

Last updated at Posted at 2020-01-06

以下の記事を参考に Go の実装に置き換えてみた。

以下のパッケージ使って同等のことが割と簡単に実装できた。

Go言語楽しい。

実行結果

# go run webrtc/main.go
2020/01/06 23:31:08 Local IP Address: 192.168.xxx.xxx
2020/01/06 23:31:08 Public IP Address: 113.xxx.xxx.xxx

実装

main.go
package main

import (
  "log"
  "os"

  "github.com/pion/webrtc/v2"
)

func main() {
  config := webrtc.Configuration{
    ICEServers: []webrtc.ICEServer{
      {
        URLs: []string{"stun:stun.l.google.com:19302"},
      },
    },
  }

  // generate a new connection
  peerConnection, err := webrtc.NewPeerConnection(config)
  if err != nil {
    log.Fatal(err)
  }

  peerConnection.OnICECandidate(func(c *webrtc.ICECandidate) {
    if c == nil {
      os.Exit(0)
    }
    switch c.Typ {
    case webrtc.ICECandidateTypeHost:
      log.Println("Local IP Address:", c.Address)
    case webrtc.ICECandidateTypeSrflx:
      log.Println("Public IP Address:", c.Address)
    }
  })

  if _, err := peerConnection.CreateDataChannel("", nil); err != nil {
    log.Fatal(err)
  }

  offer, err := peerConnection.CreateOffer(nil)
  if err != nil {
    log.Fatal(err)
  }

  if err = peerConnection.SetLocalDescription(offer); err != nil {
    log.Fatal(err)
  }

  // block forever
  select {}
}
7
6
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
7
6