码迷,mamicode.com
首页 > 其他好文 > 详细

获取机器名和IP地址

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

标签:style   blog   class   code   java   tar   

 

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地址

标签:style   blog   class   code   java   tar   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!