我如何将这个ipv6地址分配给c中的sscanf?

How can I divide this ipv6 address use to sscanf in c?

例如,我想分离这个地址。

http://[1fff:0:a88:85a3::ac1f]:8001/index.html

like..

    protocol = http
    address = 1fff:0:a88:85a3::ac1f
    port = 8001
    path = index.html

所以我使用了这个sscanf代码。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>

void main()
{
//    char url[128] = "http://10.1.35.1:8088/inedex.htm";
    char url[128] = "http://[1fff:0:a88:85a3::ac1f]:8001/index.html";
    char url_6[128], port[10], path[40];

    char *tok, *cp, *host, *proto, /**port, *path,*/ *tok6;
    char *hostbuf, *portbuf, *buf;
    int c, len, ulen, cnt_6 = 0;
    struct in6_addr result;

    ulen = strlen(url);
    len = ulen *2 + 10 + 3;

    if(strncmp(url, "http://[", 8) == 0)
    {
        tok = &url[8];
        tok[-4] = '[=11=]';
        proto = url;
        sscanf(tok, "%2000[^]]:%s", url_6, path);

        if(inet_pton(AF_INET6, url_6, &result))
        {
            printf("successful ipv6 address\n");
        }
        else
        {
            printf("Invalid ipv6 address\n");
        }
        printf("path= %s\n", path);
        printf("tok = %s\n", tok);
    }
}

但是我不明白这一行。

sscanf(tok, "%2000[^]]:%s", url_6, path); //this line is okay.

其实我是第一次写这行

//port and path is pointer.... *port, *path...
sscanf(tok, "%2000[^]]:%10[^/]%s", url_6, port, path); 

但是当我调试这一行时,出现分段错误.... 我做错了什么?
请回答这个问题。

谢谢。

你做错的是双重的:

  1. 您指定的最大宽度 sscnaf 大于您的缓冲区。
  2. 您没有告诉 sscanf 在到达分隔符后使用它们(]/)。

所以有点固定的版本(删除了你的混乱,main 使标准符合):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char url[128] = "http://[1fff:0:a88:85a3::ac1f]:8001/index.html";
    char url_6[128], port[10], path[40];

    char *tok;

    if(strncmp(url, "http://[", 8) == 0)
    {
        tok = &url[8];
        tok[-4] = '[=10=]';
        //sscanf(tok, "%2000[^]]:%s", url_6, path);
        sscanf(tok, "%127[^]]]:%9[^/]/%39s", url_6, port, path);
        //                   ^^      ^- delim '/' consumed here
        //                   |+- delim ':' consumed here
        //                   +- delim ']' consumed here

        printf("path= %s\n", path);
        printf("port= %s\n", port);
        printf("url_6 = %s\n", url_6);
    }

    return 0;
}

现场观看 here