#include "winsock2.h"
#include "iostream.h"
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"wsock32.lib")
int main(void)
{
char HostName[40];
memset(HostName,0,41);
if(gethostname(HostName,40)!=SOCKET_ERROR)
cout<<HostName<<endl;
else
cout<<"not fount!"<<endl;
hostent *host;
host=gethostbyname("LFY");//LFY为本机名
cout<<host->h_name<<endl;
return 0;
}

解决方案 »

  1.   

    应该先初始化WINSOCK.DLL啊?
    先使用WSAStartup()这个函数来初始化
      

  2.   

    在结束的时候用WSAClearup来释放资源
      

  3.   

    经过测试的代码#include "winsock2.h"
    #pragma comment(lib,"ws2_32.lib")
    #pragma comment(lib,"wsock32.lib") CString m_strIPAddress;
    WSADATA wsaData;
        int iRet = WSAStartup(MAKEWORD(0x02, 0x02), &wsaData);
        if (iRet != 0)
        {
            TRACE("初始化winsock动态库出错!");
            m_strIPAddress = "";
            return;
         }      struct in_addr localaddr;
          struct hostent *hp=NULL;
          char hostname[50];
          gethostname(hostname,49);//主机名      hp=gethostbyname(hostname);//主机信息
          memcpy(&localaddr,hp->h_addr,hp->h_length);//地址      m_strIPAddress = inet_ntoa(localaddr);//变成char *
      WSACleanup();
      

  4.   

    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2,0);
    if(WSAStartup(wVersionRequested,&wsaData) != 0)
    {
    return;
    }
    char hostname[256] = "";
    int rest = gethostname(hostname,sizeof(hostname));
    if(rest != 0)
    {
    return;
    }
    hostent* pHostent = gethostbyname(hostname);
    if(pHostent != NULL)
    {
    hostent &he = *pHostent;
    sockaddr_in sa;
    for(int nAdapter = 0 ; he.h_addr_list[nAdapter];nAdapter++)
    {
    memcpy(&sa.sin_addr.s_addr,he.h_addr_list[nAdapter],he.h_length);
    }
    SetDlgItemText(IDC_STATIC_IP,inet_ntoa(sa.sin_addr));
    }
    WSACleanup();