經過域名獲取IP地址和本機IP地址

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")

int main(int argc, char *argv[])
{
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);
    
    char webSite[80] = {0};
    puts("Enter Website:");
    gets(webSite);
    struct hostent *host = gethostbyname(webSite);
    if(!host)
    {
        puts("Get IP address error!");
        exit(0);
    }
    
    //別名
    int i;
    for(i = 0; host->h_aliases[i]; i++)
    {
        printf("Aliases %d: %s.\n", i+1, host->h_aliases[i]);
    } 
    
    //地址類型
    printf("Address type: %s\n",(host->h_addrtype == AF_INET) ? "AF_INET" : "AF_INET6");
    
    //IP地址
    for(i = 0; host->h_addr_list[i]; i++)
    {
        printf("IP addr %d: %s\n", i+1, inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
    } 
    
    /****************獲取本機IP地址*******************/
    
    //獲取本機名稱 
    char szHost[256];
    gethostname(szHost, 256);
    
    //經過本機名稱獲取本機地址信息
    HOSTENT *pHost = gethostbyname(szHost);
    if(pHost!=NULL)
    {
        //遍歷並打印本地全部IP地址
        for(i = 0; pHost->h_addr_list[i]; i++)
        {
        struct in_addr *addr = (struct in_addr*)*(pHost->h_addr_list);
        printf("本機IP %d: %s\n", i+1, inet_ntoa(addr[i]));
        }
    } 
    
    return 0; 
}
相關文章
相關標籤/搜索