首页 > 其他 > 详细

获取机器名和IP地址

时间:2014-05-09 23:40:07      阅读:445      评论:0      收藏:0      [点我收藏+]

 

VS2010/MFC/对话框

 

bubuko.com,布布扣

 

主要用两个函数:gethostname 和 gethostbyname。

  

bubuko.com,布布扣
int CIPADDRESSDlg::StartUp(void)
{
    WORD wVersionRequested;
    WSAData wsadata;
    int err;

    wVersionRequested = MAKEWORD(2, 0);
    err = WSAStartup(wVersionRequested, &wsadata);

    if (err != 0)
    {
        return err;
    }

    if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion)!= 0)
    {
        WSACleanup();
        return WSAVERNOTSUPPORTED;
    }

    return 0;
}


int CIPADDRESSDlg::CleanUp(void)
{
    int nRetCode;
    nRetCode = WSACleanup();
    if (nRetCode != 0)
    {
        return WSAGetLastError();
    }
    return 0;
}


int CIPADDRESSDlg::GetLocalHostName(CString & sHostName)
{
    char szHostName[256];
    int nRetCode;

    nRetCode = gethostname(szHostName, sizeof(szHostName));
    if (nRetCode != 0)
    {
        sHostName = TEXT("Not available");
        return WSAGetLastError();
    }

    sHostName = szHostName;
    return 0;
}

int CIPADDRESSDlg::GetIPAddress(const CString & sHostName, CString & sIpAddress)
{
    struct hostent FAR * lpHostEnt = gethostbyname(sHostName);
    if (lpHostEnt == NULL)
    {
        sIpAddress = TEXT("");
        return WSAGetLastError();
    }
    LPSTR lpAddr = lpHostEnt->h_addr_list[0];
    if (lpAddr)
    {
        struct in_addr inAddr;
        memmove(&inAddr, lpAddr, 4);
        sIpAddress = inet_ntoa(inAddr);
        if (sIpAddress.IsEmpty())
        {
            sIpAddress = TEXT("Not available");
        }
    }

    return 0;
}
bubuko.com,布布扣

 

初始化中调用:

bubuko.com,布布扣
    // TODO: 在此添加额外的初始化代码
    int nRetCode;

    nRetCode = StartUp();
    TRACE1("StartUp RetCode: %d\n", nRetCode);

    nRetCode = GetLocalHostName(m_sHostName);
    TRACE1("GetLocalHostName RetCode: %d\n", nRetCode);

    nRetCode = GetIPAddress(m_sHostName, m_sIpAddress);
    TRACE1("GetIPAddress RetCode: %d\n", nRetCode);

    nRetCode = CleanUp();
    TRACE1("CleanUp RetCode: %d\n", nRetCode);

    UpdateData(FALSE);
bubuko.com,布布扣

 

2. static text控件添加VALUE变量,m_sHostName和m_sIpAddress。

(完)

 

获取机器名和IP地址,布布扣,bubuko.com

获取机器名和IP地址

原文:http://www.cnblogs.com/fwst/p/3718757.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!