1

I have a string of the form

"http://something.another.thing:13541/random-text.txt"

I want to extract the "something.another.thing:13541" part out of it, so I am using

sscanf(uri, "http://%s/%*s", host);

To read the specified part into a buffer host. %*s should be ignoring the parts of the string after / right?

mch
  • 9,424
  • 2
  • 28
  • 42
r4bb1t
  • 1,033
  • 2
  • 13
  • 36

1 Answers1

3

The problem is not discarding parts, you need a delimiter [^?]

Try

char *uri = "http://something.another.thing:13541/random-text.txt";
char host[266];

sscanf(uri, "http://%265[^/]", host); // %265 prevents buffer overflows
printf("%s\n", host);

Since a host can not contain more than 255 bytes + say 10 for the port, char host[266]; is what you want to cover all possible cases.

Another option is to get the maximum size with getconf HOST_NAME_MAX and pass it to the program if you are under some linux.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • How does `%99` prevent buffer overflow? – r4bb1t Apr 24 '20 at 08:24
  • 2
    It means that it will write only up to 99 characters + the 0-terminator to the buffer. – mch Apr 24 '20 at 08:30
  • What if we have more than 99 characters (an unknown number) to write? – r4bb1t Apr 24 '20 at 08:38
  • You have an edit, for other cases (an unknow number of elements) you need to use other approaches, there are a lot `cs50 -> GetString`, `readline`, `getline`, a tunned `fgets` using dynamic memory ... – David Ranieri Apr 24 '20 at 09:03