C++ 将 Uint32 IP 地址转换为文本 x.x.x.x

标签 c++

我想将 Uint32 IP 地址转换为串联字符串。

在此过程中,我获得了 uint8 数据,但我需要将其更改为 const char* 以便能够将其连接到 IP 的其他部分,以便能够在一个变量中打印完整的 IP。

如何将 uint 8 更改为 const char*?或者有没有更好的方法来处理整个转换过程?

uint32 ipAddress = GetHostIp();
if (ipAddress)
 {
    const int NBYTES = 4;
        uint8 octet[NBYTES];
        int x;
        char *ipAddressFinal;
        for (x = 0; x < NBYTES; x++)
        {
             octet[x] = (ipAddress >> (x * 8)) & (uint8)-1;
        }
        for (x = NBYTES - 1; x >= 0; --x)
        {
            if (NBYTES==4)
                        {
                            const char *IPPart = octet[x]; // HERE IS THE BUG!!!!! ?
                strcpy(ipAddressFinal, IPPart);
                        }
            else
                        {
                            const char *IPPart = octet[x];  // HERE IS THE BUG!!!!! ?
                strcat(ipAddressFinal, IPPart);
                        }
            if (x > 0)
                strcat(ipAddressFinal, ".");
        }
     LogAlways("IP:   %s", ipAddressFinal);
 }

编辑

谢谢大家 - 问题解决了!谢谢大家!在很短的等待时间内得到很好的答案真是太好了!尤其要感谢 Lacrymology!!!现在这是工作代码,我不使用 Linux 我应该写下我的操作系统等...

if (ipAddress)
{
    const int NBYTES = 4;
    uint8 octet[NBYTES];
    char ipAddressFinal[16];
    for(int i = 0 ; i < NBYTES ; i++)
    {
        octet[i] = ipAddress >> (i * 8);
    }
    sprintf(ipAddressFinal, "%d.%d.%d.%d", octet[3], octet[2], octet[1], octet[0]);
    LogAlways("IP:   \"%s\"", ipAddressFinal);
}

最佳答案

我猜您使用的是 Linux - gethostip() 似乎出现在 Linux 手册页中。无论如何,如果是这样的话,使用 inet_ntoa() 怎么样? ?

sprintf(ip_src, "%s", inet_ntoa(ipdata->ip_src));

假设char* ip_src当然有足够的空间来保存一个IP地址。旨在转换 struct in_addrchar* .

包括:#include <arpa/inet.h>

关于C++ 将 Uint32 IP 地址转换为文本 x.x.x.x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4716389/

相关文章:

c++ - std::chrono::high_resolution_clock 的分辨率与测量值不对应

c++ - 使用动态库 qpOASES 和 CMakeList.txt 时出现 undefined reference to qpOASES 错误

c++ - 如何静态检查两个比率是否相等?

c++ - 如何在桌面上使用 QtMultimediaKit?

c++ - _bstr_t 内存泄漏

C++ 函数 : invalid initialization of non-const reference of type

c++ - 不同命名空间中的模板特化静态成员

c++ - 路径中左节点/子节点的最大数量

c++ - 正则表达式新手的东西

c++ - IDWriteFactory::GetSystemFontCollection 不会提供字体变体