8.2 IP地址与域名之间的转换

这节主要就是两个用C++重写过的命令行工具,用于根据域名或ipv4地址来获得目标主机的相关信息。本质上就是有关gethostbyname,gethostbyaddr两个函数与hostent结构体的内容。接下来是代码部分。


相关代码

通过域名来获得主机信息(gethostbyname.cpp)

#include 
#include 

#include 
#include 
#include 
#include 

void err_handling(const std::string &str) {
    std::cout << str << std::endl;
    exit(1);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cout << "Usage : " << argv[0] << " " << std::endl;
        exit(1);
    }

    struct hostent *host = gethostbyname(argv[1]);
    if (host == nullptr)
        err_handling(std::string("Error: can't get host..."));
    
    // output host aliases
    for(size_t cnt = 0; host->h_aliases[cnt] != nullptr; ++cnt)
        std::cout << "Aliases " << cnt + 1 << ": " << host->h_aliases[cnt] << std::endl;
    // output address type
    std::cout << "Address type: ";
    if (host->h_addrtype == AF_INET)
        std::cout << "AF_INET";
    else
        std::cout << "AF_INET6";
    std::cout << std::endl;
    // output host IP
    for(size_t cnt = 0; host->h_addr_list[cnt] != nullptr; ++cnt)
        std::cout << "IP address " << cnt + 1 << ": " << inet_ntoa(*(struct in_addr*)host->h_addr_list[cnt]) << std::endl;

    return 0;
}


通过ipv4地址来获得主机信息(gethostbyaddr.cpp)

#include 
#include 

#include 
#include 
#include 
#include 
#include 

using std::cin;
using std::cout;
using std::endl;
using std::string;

void error_handling(const string &str) {
    cout << str << endl;
    exit(1);
}

int main(int argc, char *argv[]) {
    if(argc != 2) {
        cout << "Usage : " << argv[0] << " " << endl;
        exit(1);
    }

    struct hostent *host;
    struct sockaddr_in addr;

    memset(&addr, 0, sizeof(addr));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    // only ipv4 addr is available
    host = gethostbyaddr((char*)&addr.sin_addr, 4, AF_INET);
    if (host == nullptr)
        error_handling("Error: cannot get host...");

    cout << "Official name: " << host->h_name << endl;
    for(size_t cnt = 0; host->h_aliases[cnt] != nullptr; ++cnt)
        cout << "Aliases " << cnt + 1 << ": " << host->h_aliases[cnt] << endl;
    cout << "Address type: " << ((host->h_addrtype == AF_INET) ? "AF_INET" : "AF_INET6") << endl;
    for(size_t cnt = 0; host->h_addr_list[cnt]; ++cnt)
        cout << "IP addr " << cnt + 1 << ": " << inet_ntoa(*(struct in_addr*)host->h_addr_list[cnt]) << endl;

    return 0;
}

具体用法

gethostbyname: ./gethostbyname

gethostbyaddr: ./gethostbyaddr


实际例子

gethostbyname:

zzzbkl@myUbuntu:~/INETPG/GETHOSTINFO$ ./hostdetailsbyname www.stackoverflow.com
Aliases 1: www.stackoverflow.com
Address type: AF_INET
IP address 1: 151.101.1.69
IP address 2: 151.101.129.69
IP address 3: 151.101.65.69
IP address 4: 151.101.193.69

gethostbyaddr:

zzzbkl@myUbuntu::~/INETPG/GETHOSTINFO$ ./hostdetailsbyaddr 192.30.253.112
Official name: lb-192-30-253-112-iad.github.com
Address type: AF_INET
IP addr 1: 192.30.253.112



你可能感兴趣的:(网络编程)