使用scanf将IPv6存储在C中的最佳方法是什么?

问题描述 投票:0回答:2

我目前正在尝试为分配IPv4和IPv6的任务开发程序,打印IP是前者,后者还是两者都不是。我已经弄清楚了如何使用scanf和%hhu做IPv4。但是,我不知道如何使用IPv6进行相同操作。不允许使用结构和数组。

c scanf
2个回答
-1
投票

如评论中所述,scanf()完全是错误的;即使您能够提出一种最有效的模式,这种方法也太复杂了。用这种方式构建自己的真实验证器很疯狂。

如果我正确理解了您的问题,此测试程序会提示用户输入IP地址,并测试它是IPv6还是IPv4并做出相应的响应; inet_pton()功能是标准POSIX,应该可以广泛使用。

注意:strip()函数仅用于从用户的输入行缓冲区中删除尾随的换行符,因为inet_pton()不喜欢换行符。您可能会以其他方式获得输入。

#include <stdio.h>
#include <arpa/inet.h>
#include <ctype.h>

static char *strip(char *); 

int main()
{
char    linebuf[256];

    while ( fgets(linebuf, sizeof linebuf, stdin) )
    {
    struct in_addr  addr4;
    struct in6_addr addr6;

        strip(linebuf);

        if (inet_pton(AF_INET, linebuf, &addr4) == 1)
            printf("%s is IPV4\n", linebuf);
        else if (inet_pton(AF_INET6, linebuf, &addr6) == 1)
            printf("%s is IPv6\n", linebuf);
        else
            printf("Not a valid IP address\n");
    }

    return 0;
}

// remove trailing whitespace from the given buffer
static char *strip(char *s)
{
char *s_save = s;
char *lastnsp = 0;  // last non-space

    for ( ; *s; s++)
        if ( ! isspace(*s))
            lastnsp = s;

    if (lastnsp == 0)
        *s_save = 0;
    else
        lastnsp[1] = 0;

    return s_save;
}

-2
投票

您已经提到您不能使用arraysstructures。然后,您可以使用pointers

  • 您可以使用scanf输入IPv6地址,因此必须使用ms%。在这里,您不需要使用数组或结构。
#include <stdio.h>

int main()
{
    char *IPv6;

    printf("Enter IPv4 address = ");
    scanf("%ms", &IPv6); //using %ms

    printf("IPv6 address is  = %s", IPv6);

    return 0;
}

样本输出-:

Enter IPv4 address = 2001:0db8:85a3:0000:0000:8a2e:0370:7334
Your IPv6 address is = 2001:0db8:85a3:0000:0000:8a2e:0370:7334
© www.soinside.com 2019 - 2024. All rights reserved.