【问题标题】:how to get ip address as a string如何获取IP地址作为字符串
【发布时间】:2022-07-25 22:05:42
【问题描述】:

我正在用 C 编程语言开发基于libpcap 的网络嗅探器。

我已经有了一个可以打印 IP 地址的函数,如下所示:

void print_ipaddress(ipaddress *i) {
    for (unsigned int n = 0; n < i->p_int; n++) {
        printf("%d", i->p_data[n]);
        if (n < i->p_int - 1) printf(".");
    }
    printf("\n"); 
}


ipaddress 结构由我的程序创建,数据从libpcap 复制而来。 (其实这个函数的细节你不需要关心)。以上函数可以正确打印ip地址。

下一步,我想将 IP 地址存储为字符串。所以我写了以下函数:

char* get_ipaddress(ipaddress *i) {
    char *ip = malloc(sizeof(char)*20);
    for(unsigned int n = 0; n < i->p_int; n++) {
        char s[3];
        sprintf(s, "%d", i->p_data[n]);
        strcat(ip, s);
        if (n < i->p_int - 1) {
            strcat(ip, ".");
        }
    }
    return ip;
}

但字符串中包含一些乱码如下:

I'V172.17.98.31

我有点困惑如何将每个字节作为字符串处理并将它们附加在一起。

【问题讨论】:

  • 离题:sizeof(char) 的定义是 1,所以你实际上只是添加了混乱。如果有一天您出于某种原因换成wchar_t,则需要进行调整。更喜欢char* ip = malloc(20*sizeof(*ip))。这样更安全。

标签: c string libpcap


【解决方案1】:

ip 未初始化。

char *ip = malloc(20);
ip[0] = 0;

您应该检查malloc 的结果以避免取消引用NULL 指针

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2019-08-09
    • 2021-10-15
    • 1970-01-01
    • 2012-03-06
    • 2011-02-22
    • 1970-01-01
    相关资源
    最近更新 更多