Skip to content

Instantly share code, notes, and snippets.

@fknaopen
Created December 14, 2011 04:24
Show Gist options
  • Save fknaopen/1475257 to your computer and use it in GitHub Desktop.
Save fknaopen/1475257 to your computer and use it in GitHub Desktop.
Using sscanf to get hostname from URL
#include <stdio.h>
#include <string.h>
//-------------------------
// URL INFO
//-------------------------
struct xx_url_t {
char str[1024]; /* URL strings */
};
/*------------------------------------------------------------------------------*/
/*
* @brief get hostname from URL (URL文字列からhost名を取得)
* @param [i/o] buf work-buffer
* @param [in] in URL-strings
* @retval *p host-strings
* @retval *"\0" error
*/
/*------------------------------------------------------------------------------*/
char * func_cut_host( struct xx_url_t *buf, const char * in )
{
static char *blank = "\0";
int err;
char *p;
// check argument
if ( buf != NULL && in != NULL ){
// check buffer overflow
if ( sizeof(buf->str) > strlen(in) ) {
// get 2nd part.
// ex:"http://www.a.b.c/cgi/jobs.cgi?h=99&z=3" -> www.a.b.c
// ex:"file:///tmp/test.txt" -> tmp
err = sscanf( in, "%*[^/]%*[/]%[^/]", buf->str);
if ( 1 == err ) {
p = buf->str;
} else {
// sscanf error
p = blank;
}
}else {
// buffer overflow
p = blank;
}
}else {
// invalid argument
p = blank;
}
return p;
}
// test
main() {
struct xx_url_t buf;
char *url;
url = "http://www.a.b.c/cgi/jobs.cgi?h=99&z=3";
printf( "URL[%s] -> host[%s]\n", url, func_cut_host( &buf, url ));
}
@neosarchizo
Copy link

Good! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment