此代码永无止境,尽管返回正确的IP地址,但可以无限运行

时间:2019-07-11 16:03:52

标签: c++ network-programming

我是C ++网络编程的新手。我最近使用了 getaddinfo(),并且遇到了一些困难。 首先,我想知道“一个或多个addrinfo结构的链接列表”是什么。对于我来说,是否返回整个addrinfo或只是指向它的指针,这一点我不清楚。如果返回了结构,则将其存储在何处;如果返回了指针,则该指针将指向本地还是联机?

#include <iostream>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>

using namespace std;


int main(int argc, char *argv[]) {
    struct addrinfo hints, *res, *p;
    int status;
    char ipstr[INET_ADDRSTRLEN];

    if (argc != 2) {
        cerr << "\nUsage: showip hostname";
        return 1;
    }

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if ((status == getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
        cerr << "\nGetAddressInfo:" << gai_strerror(status);
        //return 2;
    }

    cout << "IP address for " << argv[1];

    for (p = res; p != NULL; p->ai_next) {
        void *addr;
        char *ipver;

        if (p->ai_family == AF_INET) {
            struct sockaddr_in *ipv4 = (struct sockaddr_in *) p->ai_addr;
            addr = &(ipv4->sin_addr);
            ipver = "IPv4";
        } else {
            struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *) p->ai_addr;
            addr = &(ipv6->sin6_addr);
            ipver = "IPv6";
        }

        inet_ntop(p->ai_family, addr, ipstr, sizeof(ipstr));
        cout << ipver << ": " << ipstr;
    }

    freeaddrinfo(res);
    return 0;

}

0 个答案:

没有答案