原文http://www.360doc.com/content/14/0514/11/1123425_377486376.shtml
#include
#include
#include
#include
#include
#include
#include
#include
#include

int main(int argc, char** argv)
{
    assert(argc == 2);
    const char* hostname = argv[1];
    struct hostent* host;

    host = gethostbyname(hostname);
    if (NULL == host)
    {
        perror("can not get host by hostname");
        exit(EXIT_FAILURE);
    }

    printf("host ip=%s\n", inet_ntoa(*((struct in_addr*)host->h_addr)));
    return EXIT_SUCCESS;
}

本人文峰聊书斋在centos6平台验证
[root@www ble_mesh]# ./a.out www.baidu.com
host ip=14.215.177.38
[root@www ble_mesh]#
文峰聊书斋另外加入:
#define SOCKADDR_IN(addr, ip, port) do{ \
                                memset(&(addr), 0, sizeof(addr)); \
                                (addr).sin_family      = AF_INET;     \
                                (addr).sin_addr.s_addr = inet_addr(ip);   \
                                (addr).sin_port        = htons(port);     \
                                if ((addr).sin_addr.s_addr == INADDR_NONE){    \
                                    struct hostent* pHost = gethostbyname(ip);  \
                                    if (pHost == NULL){return ;}  \
                                    memcpy(&(addr).sin_addr, pHost->h_addr_list[0], pHost->h_length);} \
                                }while(0)

    struct sockaddr_in servaddr;
    SOCKADDR_IN(servaddr,"www.baidu.com", 5000);
    //SOCKADDR_IN(servaddr,"192.168.0.11", 5000);
    printf("baidu%s\n",inet_ntoa(servaddr.sin_addr));
12-09 22:50
查看更多