例如,我想分离这个地址。
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] = '\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);
}
}
但是我不明白这一行。
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);
但是当我调试这一行时,出现段错误....
我做错了什么?
请回答这个问题。
谢谢。
最佳答案
你做错的是双重的:
- 您为
sscnaf
指定的最大宽度大于您的缓冲区。 - 您不会告诉
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] = '\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;
}
现场观看here .
关于c - 我如何将这个ipv6地址分配给c中的sscanf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38737547/