簡體   English   中英

將輸入字符串轉換為IP地址格式

[英]Convert an input string to Ip address format

我正在從數據庫中以字符串格式讀取IP地址,但我想以IP格式(例如192.168.100.155)顯示它們

char formatAs_Ipaddress(const char *str)

此函數將以IP地址的形式格式化傳遞給它的字符串,即255001001001將返回255.1.1.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;
}
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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM