C ++从URL解析主机IP地址 [英] C++ Resolve a host IP address from a URL

查看:1253
本文介绍了C ++从URL解析主机IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过 Visual C ++中的URL解析主机IP地址?

How can I resolve a host IP address, given a URL in Visual C++?

推荐答案

要使用Windows下的套接字函数,您必须通过调用 WSAStartup 开始,指定所需的Winsock版本(为了您的目的,1.1将正常工作)。然后可以调用 gethostbyname 获取主机的地址。当你完成后,你应该调用WSACleanup。把所有的东西放在一起,你会得到这样的:

To use the socket functions under Windows, you have to start by calling WSAStartup, specifying the version of Winsock you want (for your purposes, 1.1 will work fine). Then you can call gethostbyname to get the address of the host. When you're done, you're supposed to call WSACleanup. Putting that all together, you get something like this:

#include <windows.h>
#include <winsock.h>
#include <iostream>
#include <iterator>
#include <exception>
#include <algorithm>
#include <iomanip>

class use_WSA { 
    WSADATA d; 
    WORD ver;
public:
    use_WSA() : ver(MAKEWORD(1,1)) { 
        if ((WSAStartup(ver, &d)!=0) || (ver != d.wVersion))
            throw(std::runtime_error("Error starting Winsock"));
    }
    ~use_WSA() { WSACleanup(); }    
};

int main(int argc, char **argv) {
    if ( argc < 2 ) {
        std::cerr << "Usage: resolve <hostname>";
        return EXIT_FAILURE;
    }

    try { 
        use_WSA x;

        hostent *h = gethostbyname(argv[1]);
        unsigned char *addr = reinterpret_cast<unsigned char *>(h->h_addr_list[0]);
        std::copy(addr, addr+4, std::ostream_iterator<unsigned int>(std::cout, "."));
    }
    catch (std::exception const &exc) {
        std::cerr << exc.what() << "\n";
        return EXIT_FAILURE;
    }

    return 0;
}

编辑:删除代码将基础设置为16 -

removed code to set the base to 16 -- IP addresses are usually printed in decimal.

这篇关于C ++从URL解析主机IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆