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

lua*_*uac 2 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);
 }
Run Code Online (Sandbox Code Playgroud)

编辑

谢谢大家-问题解决了!谢谢大家!在很短的等待时间内获得很好的答案真是太好了!特别要感谢泪谱学!!!现在这里是工作代码,我不使用Linux,我应该写下我的OS等。

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);
}
Run Code Online (Sandbox Code Playgroud)

小智 8

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

sprintf(ip_src, "%s", inet_ntoa(ipdata->ip_src));
Run Code Online (Sandbox Code Playgroud)

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

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


nos*_*nos 5

怎么样

uint32 ipAddress = GetHostIp();
if (ipAddress) {
    char ipAddr[16];
    snprintf(ipAddr,sizeof ipAddr,"%u.%u.%u.%u" ,(ipAddress & 0xff000000) >> 24 
                                                ,(ipAddress & 0x00ff0000) >> 16
                                                ,(ipAddress & 0x0000ff00) >> 8
                                                ,(ipAddress & 0x000000ff));
    // depending on the byte order your GetHostIp() returns the IP address in
    // you might need to reverse the above (i.e. print (ipAddress &0x000000ff)) first.
    LogAlways("IP:   %s", ipAddr);
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用inet_ntoagetnameinfo将IP地址转换为字符串。