msdn中找不到getaddrbyhost,请举个例子怎么用。

解决方案 »

  1.   

    WSADATA wsa;
    WSAStartup(0x0101,&wsa);
    struct sockaddr_in addr;
    SOCKET s;
    struct hostent* p=gethostbyname("smtp.netease.com");
    if(!p){
    m_status+="\r\nError get IP.";
    GetDlgItem(IDC_STATUS)->SetWindowText(m_status);
    return;
    }
    s=socket(AF_INET,SOCK_STREAM,0);
    addr.sin_family=AF_INET;
    addr.sin_port=htons(25);
    addr.sin_addr.s_addr = *(unsigned long*)p->h_addr;connect(s,/*IP*/(struct sockaddr*)&addr,sizeof(addr));
      

  2.   

    下面的代码返回本机的机器名和Ip地址,要查询其他机器的IP地址,只要将其中的hostname改为其他机器名即可。
    测试通过:VC6.0+Win2k Prof.
    //要求Ws2_32.lib
    #include <windows.h>#define MAXLEN   128int WINAPI WinMain(HINSTANCE hInstance,
     HINSTANCE hPrevInstance,
     LPTSTR lpCmdLine,
     int nCmdSHow)
    {
    WORD wVersionRequested;
    WSADATA wsaData;
    int ret;
    TCHAR msg[MAXLEN];

    wVersionRequested = MAKEWORD( 2, 2 ); ret = WSAStartup( wVersionRequested, &wsaData );
    if ( ret != 0 ) {
    wsprintf(msg,TEXT("Could not find a usable Winsock DLL"));
    MessageBox(NULL,msg,TEXT("Error"),MB_OK);
    return 1;
    }

    if (LOBYTE( wsaData.wVersion ) != 2 ||
            HIBYTE( wsaData.wVersion ) != 2 )
    {
    wsprintf(msg,TEXT("Could not find a usable Winsock2.0 DLL"));
    MessageBox(NULL,msg,TEXT("Error"),MB_OK);
    WSACleanup( );
    return 2; 
    }

    char hostname[MAXLEN];
    HOSTENT *lpHost=NULL;
        struct sockaddr_in dest; if((ret = gethostname(hostname, MAXLEN)) != 0)
    {
    wsprintf(msg, TEXT("Error calling gethostname: %d"), ret);
            MessageBox(NULL, msg, TEXT("Error"), MB_OK);     
    }
    else
    {
    wsprintf(msg, TEXT("Hostname is: %s"), hostname);
            MessageBox(NULL, msg, TEXT("Info"), MB_OK);     

    lpHost = gethostbyname(hostname);
    if(lpHost==NULL)
    {
    wsprintf(msg, TEXT("Error calling gethostbyname: %d"), WSAGetLastError());
    MessageBox(NULL, msg, TEXT("Error"), MB_OK);     
    }
    else
    {
    for(int i=0; lpHost->h_addr_list[i]!=NULL;i++)
    {
    memcpy(&(dest.sin_addr),lpHost->h_addr_list[i],lpHost->h_length);
    wsprintf(msg,TEXT("Ip Address: %s"),inet_ntoa(dest.sin_addr));
    MessageBox(NULL, msg, TEXT("Info"), MB_OK);     
    }
             
    }
    }
          
    WSACleanup( );
    return 0;
    }
       

      

  3.   

    请问怎样设置本地网卡的IP地址?用sethostname吗?