简体   繁体   中英

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

For example , I want to separate this address.

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

like..

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

So I used this sscanf code.

#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] = '\0';
        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);
    }
}

But I don't understand this line.

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

Actually, it's the first time, I'm writing this line.

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

but when I debug this line, then segmentation fault accurs.... What did I do wrong ?
please answer this question.

thanks.

What you did wrong is twofold:

  1. You specify maximum widths to sscnaf which are larger than your buffers.
  2. You don't tell sscanf to consume your delimiters after you reach them ( ] and / ).

So a somewhat fixed version (with your clutter removed, and main made standard conforming):

#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] = '\0';
        //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;
}

See it live here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM