我想将 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_addr
至 char*
.
包括:#include <arpa/inet.h>
关于C++ 将 Uint32 IP 地址转换为文本 x.x.x.x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4716389/