Created
December 14, 2011 04:24
-
-
Save fknaopen/1475257 to your computer and use it in GitHub Desktop.
Using sscanf to get hostname from URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 )); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good! Thanks!