C++ Socket库IP地址转换技巧

发布时间:2024-10-27 16:10:05 作者:小樊
来源:亿速云 阅读:81

在C++中,使用Socket库进行IP地址转换时,主要涉及到IPv4和IPv6地址之间的转换,以及主机名与IP地址之间的转换。以下是一些常用的技巧和步骤:

  1. IPv4到IPv6的转换

示例代码:

#include <arpa/inet.h>
#include <iostream>
#include <string>

int main() {
    const char* ipv4_str = "192.168.1.1";
    struct in_addr ipv4;
    if (inet_pton(AF_INET, ipv4_str, &ipv4) == 1) {
        char ipv6[INET6_ADDRSTRLEN];
        if (inet_ntop(AF_INET6, &ipv4, ipv6, INET6_ADDRSTRLEN) != nullptr) {
            std::cout << "IPv6 address: " << ipv6 << std::endl;
        } else {
            std::cerr << "inet_ntop failed" << std::endl;
        }
    } else {
        std::cerr << "inet_pton failed" << std::endl;
    }
    return 0;
}
  1. IPv6到IPv4的转换

示例代码:

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

int main() {
    const char* hostname = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
    struct addrinfo hints, *result;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if (getaddrinfo(hostname, nullptr, &hints, &result) != 0) {
        fprintf(stderr, "getaddrinfo failed\n");
        return 1;
    }

    struct sockaddr_in6* ipv6_addr = (struct sockaddr_in6*)result->ai_addr;
    char ipv4[INET_ADDRSTRLEN];
    if (inet_ntop(AF_INET6, &(ipv6_addr->sin6_addr), ipv4, INET_ADDRSTRLEN) != nullptr) {
        std::cout << "IPv4 address: " << ipv4 << std::endl;
    } else {
        std::cerr << "inet_ntop failed" << std::endl;
    }

    freeaddrinfo(result);
    return 0;
}
  1. 主机名到IP地址的转换

示例代码:

#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

int main() {
    const char* hostname = "www.example.com";
    struct hostent* result = gethostbyname(hostname);
    if (result == nullptr) {
        fprintf(stderr, "gethostbyname failed\n");
        return 1;
    }

    struct in_addr* ipv4_addr = (struct in_addr*)result->h_addr;
    char ipv4_str[INET_ADDRSTRLEN];
    if (inet_ntop(AF_INET, ipv4_addr, ipv4_str, INET_ADDRSTRLEN) != nullptr) {
        std::cout << "IPv4 address: " << ipv4_str << std::endl;
    } else {
        std::cerr << "inet_ntop failed" << std::endl;
    }

    return 0;
}

注意:在使用这些函数时,请确保处理可能的错误情况,并释放分配的资源。

推荐阅读:
  1. c++ ip6编程
  2. C++中socket如何实现跨平台

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:如何在C++中模拟super的功能特性

下一篇:C++继承体系下的super行为模拟

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》