I am writing a simple but secure HTTP/1.0 client, for an assignment. The client should send a GET request to some server, and parse the server response into tokens, such as:
Initial line
Last-Modified:
Content-Type
Body:
I've found much documentation about socket programming, but nothing about how to properly tokenize the server response. Can someone point me in the right direction. This is the only way I could get things to somewhat work:
Code:
int clientResponse(int socket, char *version, char *code, char *message, char *server, char *lastModified, char *date, char *contentType, char *contentLength, char *body){
char buf[MAX_FILE_SIZE]; // buffer to hold the incoming socket message
char *ptrPosition; // pointer used for seeking
int nr=0; // number of bytes read from socket
int numScan=0; // number of bytes parsed in buffer
int numTokens=0; // number of tokens found
char *headerName; // temp buffer for header field-name
char *headerValue; // temp buffer for header field-value
// get message
if((nr = getMessage(socket, buf, MAX_FILE_SIZE)) <= 0){
return -1;
}
// get starting position of message
ptrPosition = buf;
if((headerName = malloc(BUF_SIZE)) == NULL){
return -2;
}
if((headerValue = malloc(BUF_SIZE)) == NULL){
return -2;
}
// tokenize initial line
if((numTokens = sscanf(ptrPosition, "%s %s %255[^\r\n]\r\n%n", version, code, message, &numScan)) != 3){
return -3;
}
// move pointer position
ptrPosition += numScan;
// tokenize headers
while((numTokens = sscanf(ptrPosition, "%255[^:]: %255[^\r\n]\r\n%n", headerName, headerValue, &numScan)) == 2){
// check for body
if(headerName[0] == '<'){
strcpy(body, ptrPosition);
break;
}
// move position
ptrPosition += numScan;
// set appropriate header token
if(strcmp(headerName, "Date") == 0){
strcpy(date, headerValue);
}
if(strcmp(headerName, "Server") == 0){
strcpy(server, headerValue);
}
if(strcmp(headerName, "Last-Modified") == 0){
strcpy(lastModified, headerValue);
}
if(strcmp(headerName, "Content-Length") == 0){
strcpy(contentLength, headerValue);
}
if(strcmp(headerName, "Content-Type") == 0){
strcpy(contentType, headerValue);
}
}
// deallocate memory
free(headerName);
free(headerValue);
return nr;
}