将输入字符串转换为IP地址格式

时间:2013-12-14 21:02:24

标签: c string ip-address string-formatting string-parsing

我正在以字符串格式从数据库中读取IP地址,但我想以IP格式显示它们,如192.168.100.155

char formatAs_Ipaddress(const char *str)

此函数将格式化以IP地址形式传递给它的字符串,即255001001001将返回为255.1.1.1

我可以为查询获得更优化的方式吗?

2 个答案:

答案 0 :(得分:1)

我尝试这样做,它对我有用。

char formatAs_Ipaddress(const char* str)    {
    char getval;
    if(str!=0)  {
        char temp[256]; memset(temp,0,256);
        int len = strlen(str);
        int cnt = 0;
        for(int i=0,j=0;i<len;++i)  {
            temp[j] = str[i];
            if(i>=11)   {
                break;
            }
            ++j;
            ++cnt;
            if(cnt!=0 && cnt%3==0)  {
                temp[j]='.';
                ++j;
            }
        }
        getval  = temp;
    }
    return getval;
}

答案 1 :(得分:0)

char *format_ipaddress(const char *input, char *output, int size) 
{
    if (input == NULL || output == NULL || size < 16) // invalid parameters
        return NULL;

    int len = strlen(input);
    if (len != 12) // input looks invalid
        return NULL;

    char *outptr = output;
    for(int i = 0; i <= 9; i += 3)
    {
        char *inptr = input + i;
        int inlen = 3;
        while (inlen > 1 && *inptr == '0')
        {
           // remove zeros at beginning of subnet block
           ++inptr;
           --inlen;
        }

        memcpy(outptr, inptr, inlen);
        outptr += inlen; 

        if (i < 9)
           *outptr++ = '.';
    }
    *outptr = 0; // ensure output ends with a \0

    return output;
}


char *input = "192168010010";
char output[16];
char *result;

result = format_ipaddress(input, output, sizeof(output));
if (result != NULL)
{
    printf("'%s' formated as ip address: '%s'", input, result);
}
else
{
    printf("Something went wrong. Check your input.\n");
}