0
0

More than 3 years have passed since last update.

【GoネットワークプログラムでIPv6対応させる】自分のグローバルアドレスを知る方法

Last updated at Posted at 2020-08-07

理由

ネットワークプログラムで、自身のグローバルIPアドレスを知る必要がある場合がある。その場合のコード例をメモしておく

参考コード

main.go
package main

import (
    "fmt"
    "github.com/skubota/extip"
)

func main() {
    addr,err := extip.GetIP()
    if err != nil {
        fmt.Errorf("Address cannot get : %s\n", err)
    }else{
        fmt.Printf("Adress : %s\n",addr) 
    }
}
  • 結果(IPv6/IPv4対応クライアント)
Adress : 2xxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
  • 結果(IPv4のみ対応クライアント)
Adress : 2xx.xxx.xxx.xxx

解説

標準パッケージではないが、「skubota/extip」というIPv6対応のSTUNで通信のあったソースIPアドレスを知ることができます。

アンチパターン

あまり、これがアンチパターンだというものはないかと思いますが、IPv4のみの返答しかできないHTTPサーバやDNSサーバを使ったライブラリやコードがあるので注意が必要です。

まとめ

IPv6対応のパッケージ・コードとなっているか確認しよう

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