Last active
December 17, 2015 18:29
-
-
Save keiya/5653834 to your computer and use it in GitHub Desktop.
URI Parser in C: hostとpathに分割するので,SocketでHTTP系の処理するときにラクだと思う.
ポインタ操作のオンパレード.
This file contains hidden or 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
| typedef struct uri { | |
| char host[REQ_HEAD_HOST_SZ]; | |
| char *path; | |
| char *filename; | |
| int port; | |
| } Uri; | |
| int | |
| parse_uri(char uri[], Uri *parsed) | |
| { | |
| char *host = strstr(uri,"://"); | |
| if (host == NULL) return 0; | |
| host += 3; | |
| char *path = strstr(host,"/"); | |
| if (path == NULL) { | |
| if ((uri = realloc(uri,strlen(uri)+2)) == NULL) { | |
| perror("malloc"); | |
| exit(1); | |
| } | |
| if ((path = realloc(path,2)) == NULL) { | |
| perror("malloc"); | |
| exit(1); | |
| } | |
| strlcpy(path,"/",2); | |
| strlcat(uri,path,strlen(uri)+3); | |
| host = strstr(uri,"://") + 3; | |
| path = strstr(host,"/"); | |
| } | |
| if ((parsed->path = malloc(strlen(path)) + 1) == NULL) { | |
| perror("malloc"); | |
| exit(1); | |
| } | |
| strlcpy(parsed->path,path,strlen(path) + 1); | |
| char *ret; | |
| if ((ret = strrchr(path,'/'))) { | |
| if ((parsed->filename = malloc(strlen(++ret) + 1)) == NULL) { | |
| perror("malloc"); | |
| exit(1); | |
| } | |
| if (strlen(ret) == 0) | |
| ; | |
| else | |
| strlcpy(parsed->filename,ret,strlen(ret) + 1); | |
| } | |
| char *port; | |
| if ((port = strstr(host,":")) != NULL) { | |
| int bytes = 0; | |
| *port++; | |
| while (isdigit(*port)) { | |
| *port++; | |
| ++bytes; | |
| } | |
| if (bytes > 0) { | |
| port[0] = '\0'; | |
| parsed->port = atoi(port-bytes); | |
| *(host+strlen(host)-bytes-1) = '\0'; | |
| } | |
| } | |
| else { | |
| parsed->port = 80; | |
| } | |
| *(host+strlen(host)-strlen(path)) = '\0'; | |
| strlcpy(parsed->host,host,256); | |
| return 1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment