[VB.net]グローバルIPアドレス取得(curlコマンド)
VB.NETでのグローバルIPアドレスの取得方法が調べても
ルータにアクセスして取得する方法やローカルIPアドレスの取得くらいしか載っていなかったので
簡潔に書いておきます。
方法
・VB.NET上で「curl」コマンドを使用し「https://inet-ip.info/」からIPアドレスを取得
curl inet-ip.info
または
curl inet-ip.info/ip
・下記は実際に取得するためのコード例
Private Function Cmd_IPaddress_Get() As String
Try
'Processオブジェクトを作成
Dim cmd As New System.Diagnostics.Process()
'ComSpec(cmd.exe)のパスを取得して、FileNameプロパティに指定
cmd.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec")
'出力を読み取れるようにする
cmd.StartInfo.UseShellExecute = False
cmd.StartInfo.RedirectStandardOutput = True
cmd.StartInfo.RedirectStandardInput = False
'ウィンドウを表示しないようにする
cmd.StartInfo.CreateNoWindow = True
'コマンドラインを指定(先頭の「/c」は実行後閉じるために必要)
cmd.StartInfo.Arguments = "/c curl inet-ip.info/ip"
'起動
cmd.Start()
'出力を読み取る
Dim results As String = cmd.StandardOutput.ReadToEnd()
'プロセス終了まで待機する
'WaitForExitはReadToEndの後である必要がある(親プロセス、子プロセスでブロック防止のため)
cmd.WaitForExit()
cmd.Close()
'出力された結果を表示
Return results '.Trim() ※1
Catch ex As Exception
Return String.Empty
End Try
End Function
※1「curl inet-ip.info」を使用した場合は「 & vbLf」が返される文字列に付加されているのでTrim関数で消す必要があります。
ローカルIPアドレスの場合は下記の2行で取得できます。
'ホスト名(フルコンピューター名)を取得
Dim strHostName As String = System.Net.Dns.GetHostName()
'取得したホスト名からローカルIPを取得
Dim LocalAddress As System.Net.IPAddress() = System.Net.Dns.GetHostAddresses(strHostName)
最後に
有料ではあるものの他にも色々取得できるようだがグローバルIPだけちゃっと取得したかったので他の物は割愛します(調べると結構出てきますし・・・)
他にもグローバルIPを表示するサイトのhtmlからstringで持ってきたりもできますがこちらの方法の方が早いのでメモ代わりに置いておきます。
ディスカッション
コメント一覧
You have brought up a very fantastic details , regards for the post. Consuela Patty Grory
Good post! We will be linking to this particularly great article on our site. Keep up the great writing. Kelcey Roosevelt Micco
This betters your chances of finding open spots on the field and increases the amount of space for you to execute a plan. Lorry Alan Adolphe