ホスト名からIPアドレスを取得するには

今回はホスト名からIPアドレスを取得してみます。
キーワードは「inet_addr()関数」と「gethostbyname()関数」です。
inet_addr()関数はホスト名からIPアドレスを取得してくれる関数です。
gethostbyname()関数はホスト名を使用してホスト情報を取得してくれる関数です。

ますWinSockAPIを「WSAStartup()関数」で初期化します。
初期化に成功したらinet_addr関数にホスト名を渡します。

もし渡されたホスト名が無効だったらinet_addr()関数は失敗します。
成功したらgethostbyname()関数を使ってhostent構造体へのポインタを取得します。

あとはhostent構造体のポインタからホストに関する情報を取得します。

実行時の様子

Private Sub Command1_Click()
Dim host_path As String
Dim VerReq As Integer, rc As Long
Dim wsaDD As wsaDATA
Dim HostAddress As Long, lphostinfo As Long
Dim HostEntCopy As hostent, AddressListPoint As Long
Dim lpHostAddress As lpHostAddress

Me.Command1.Enabled = False
host_path = Me.Text1.Text

'@WinSockAPIの初期化
VerReq = MakeInteger(1, 1)                      'WinSock1.1を要求
rc = WSAStartup(VerReq, wsaDD)
If rc <> 0 Then
    'Winsockリソースの確保に失敗
    MsgBox "WinSockの初期化失敗", , "Error"
    Exit Sub
End If

'A送信先のIPアドレスの取得
HostAddress = inet_addr(host_path)              'IPアドレスに変換(数値の場合 ex:127.0.0.1)
If HostAddress = INADDR_NONE Then
    '変換できなかった場合
    
    lphostinfo = gethostbyname(host_path)
    If lphostinfo <> 0 Then
        'hostent構造体をコピー
        Call MoveMemory(HostEntCopy, ByVal lphostinfo, Len(HostEntCopy))
        'アドレスリストのアドレスを取得
        Call MoveMemory(AddressListPoint, ByVal HostEntCopy.h_addr_list, Len(AddressListPoint))
        'アドレスリストの先頭値を取得
        Call MoveMemory(HostAddress, ByVal AddressListPoint, Len(HostAddress))
        Call MoveMemory(lpHostAddress, ByVal AddressListPoint, Len(HostAddress))
        With lpHostAddress
            MsgBox "[HostName]->" & .szhostAddress(0) & "." & .szhostAddress(1) & _
                  "." & .szhostAddress(2) & "." & .szhostAddress(3)
        End With
    Else
        'ポインタが取得できなかった
        MsgBox "ホスト名からIPアドレスが取得できませんでした"
        Exit Sub
    End If
End If
Call WSACleanup                                 'WinSockのクローズ

Me.Command1.Enabled = True
End Sub

Private Sub Form_Load() Me.Text1.Text = "www.winapi-database.com" Me.Command1.Enabled = True End Sub
Private Sub Text1_Change() Dim txt As String txt = Me.Text1.Text If txt = "" Then Me.Command1.Enabled = False Else Me.Command1.Enabled = True End If End Sub
ダウンロード