ZBLOG

inet_ntop将整数转换为IP地址

inet_ntop() 是一个用于将二进制整数形式的网络地址(如 IPv4/IPv6)转换为人类可读的字符串格式(如 "192.168.1.1")的函数,属于套接字编程中的常用工具。以下是详细说明和示例:


函数原型

#include <arpa/inet.h>

const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);

参数说明

参数 类型 描述
af int 地址族:AF_INET(IPv4)或 AF_INET6(IPv6)。
src const void* 指向二进制网络地址的指针(如 struct in_addrstruct in6_addr)。
dst char* 存储转换后字符串的缓冲区。
size socklen_t 缓冲区 dst 的大小(通常用宏如 INET_ADDRSTRLEN, INET6_ADDRSTRLEN)。

返回值

  • 成功:返回指向字符串地址的指针(即 dst)。
  • 失败:返回 NULL,并设置 errno

使用示例

1. IPv4地址转换

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

int main() {
    struct in_addr addr;
    addr.s_addr = htonl(0xC0A80101); // 二进制形式:192.168.1.1

    char ip_str[INET_ADDRSTRLEN]; // IPv4缓冲区大小至少16字节
    if (inet_ntop(AF_INET, &addr, ip_str, sizeof(ip_str))) {
        printf("IPv4 Address: %s\n", ip_str); // 输出:192.168.1.1
    } else {
        perror("inet_ntop failed");
    }
    return 0;
}

2. IPv6地址转换

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

int main() {
    struct in6_addr addr6 = IN6ADDR_ANY_INIT; // ::0 (全零地址)
    
    char ip6_str[INET6_ADDRSTRLEN]; // IPv6缓冲区大小至少46字节
    if (inet_ntop(AF_INET6, &addr6, ip6_str, sizeof(ip6_str))) {
        printf("IPv6 Address: %s\n", ip6_str); // 输出:::
    } else {
        perror("inet_ntop failed");
    }
    return 0;
}

关键注意事项

  1. 线程安全

    • inet_ntop() 是线程安全的,但需确保目标缓冲区 (dst) 不被其他线程修改。
  2. 缓冲区大小

    • IPv4:使用宏 INET_ADDRSTRLEN(16字节)。
    • IPv6:使用宏 INET6_ADDRSTRLEN(46字节)。
  3. 错误处理

    • 检查返回值是否为 NULL,并通过 errno 定位问题:
      
      if (!inet_ntop(...)) { 
       perror("Error"); 
      }
      
  4. 替代函数对比

    • 不推荐:旧版函数如 inet_ntoa() 是非线程安全的。

如果需要进一步探讨网络编程的其他接口或场景,可以随时提问!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=8278

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?