如题!

解决方案 »

  1.   

    CString CDYUtility::GetLocalIP()
    {
    WORD wVersionRequested;
    WSADATA wsaData;

    wVersionRequested = MAKEWORD( 2, 2 );

    int err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 ) {
    SetErrorNumber(DY_SOCKET_DLL_ERROR);
    return _T("127.0.0.1");
    }

    if ( LOBYTE( wsaData.wVersion ) != 2 ||
            HIBYTE( wsaData.wVersion ) != 2 ) 
    {
    /* Tell the user that we could not find a usable *
    /* WinSock DLL.                                  */
    WSACleanup( );
    SetErrorNumber(DY_SOCKET_DLL_ERROR);
    return _T("127.0.0.1");; 
    }

    TCHAR szHostName[128];
    memset(szHostName,0,sizeof(TCHAR)*128);
    PTSTR lpszAddr = szHostName;
    if (gethostname(szHostName, sizeof(szHostName)) == SOCKET_ERROR) 
    lstrcpy(lpszAddr, "127.0.0.1");
    else 
    {
    LPHOSTENT lpHostent = gethostbyname(szHostName);
    if ((lpHostent != NULL) && (lpHostent->h_addr_list[0] != NULL))
    {
    struct in_addr Addr;
    memcpy(&Addr.s_addr, lpHostent->h_addr_list[0], 
    sizeof(Addr.s_addr));
    lpszAddr = inet_ntoa(Addr);
    if (lpszAddr == NULL)
    lstrcpy(lpszAddr, "127.0.0.1");

    else 
    lstrcpy(lpszAddr, "127.0.0.1");
    }
    CString str = lpszAddr;
        WSACleanup(); 
    return str;
    }