[英]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. 所以我用了这个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] = '\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: 您做错了两点:
sscnaf
which are larger than your buffers. 您可以为sscnaf
指定最大宽度,该最大宽度大于缓冲区的宽度。 sscanf
to consume your delimiters after you reach them ( ]
and /
). 到达分隔符( ]
和/
)后,您不会告诉sscanf
使用它们。 So a somewhat fixed version (with your clutter removed, and main
made standard conforming): 因此,有些固定的版本(消除了您的混乱,并使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] = '\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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.