Windows上的vc ++ ipconfig cmd等效项

时间:2009-12-22 19:43:49

标签: windows visual-c++ ipconfig

如何在VC ++中实现Windows上ipconfig中给出的功能?我需要获取机器的本地ip信息,primary ip vs。

1 个答案:

答案 0 :(得分:1)

好人,以前我找不到有用的东西,但我在this link找到了解决方案。

// GetLocalIP.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <winsock2.h>

int _tmain(int argc, _TCHAR* argv[])
{
    // Add 'ws2_32.lib' to your linker options

    WSADATA WSAData;

    // Initialize winsock dll
    if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
    {
        // Error handling
    }

    // Get local host name
    char szHostName[128] = "";

    if(::gethostname(szHostName, sizeof(szHostName)))
    {
        // Error handling -> call 'WSAGetLastError()'
    }

    // Get local IP addresses
    struct sockaddr_in SocketAddress;
    struct hostent     *pHost        = 0;

    pHost = ::gethostbyname(szHostName);
    if(!pHost)
    {
        // Error handling -> call 'WSAGetLastError()'
    }

    char aszIPAddresses[10][16]; // maximum of ten IP addresses

    for(int iCnt = 0; ((pHost->h_addr_list[iCnt]) && (iCnt < 10)); ++iCnt)
    {
        memcpy(&SocketAddress.sin_addr, pHost->h_addr_list[iCnt], pHost->h_length);
        strcpy(aszIPAddresses[iCnt], inet_ntoa(SocketAddress.sin_addr));
        //std::cout << aszIPAddresses[iCnt] << endln;
    }

    // Cleanup
    WSACleanup();

    return 0;
}