/* Protocol: * Format: * type (1 byte) * next part depends on the type * Client can send: * 1. Report of squirrels * Client sends the type (1) as a byte * Then client sends the number of squirrels observed (32-bit unsigned integer, little endian) * 2. Query * Client sends the type (2) as a byte * Server can send: * 3. An acknowledgement of a report * Server sends the type (3) as a byte * 4. Send total number of squirrels * Server sends the type (4) as a byte * Then server sends the total number of squirrels recorded (32-bit unsigned little-endian integer) */ #include #include #include #include #include #include #include int main(int argc, char ** argv){ struct sockaddr_in sad; sad.sin_port = htons(5143); sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_STREAM, 0); // Step 1 if(skt == -1){ perror("socket"); return 1; } if( bind(skt, (struct sockaddr*)(&sad), sizeof(struct sockaddr_in)) ){ // step 2 perror("bind"); return 1; } if( listen(skt, 5) ){ // step 3 perror("listen"); return 1; } uint32_t squirrel_count = 0; while(1){ int client_fd; struct sockaddr_in client_address; socklen_t address_size = sizeof(struct sockaddr_in); client_fd = accept(skt, (struct sockaddr *)(&client_address), &address_size); // step 4 printf("Connection made from address %s\n", inet_ntoa(client_address.sin_addr)); uint8_t type = 0; // Same as "unsigned char" ssize_t readlen = read(client_fd, &type, 1); if(readlen == -1) perror("read"); if(readlen == 0) printf("readlen was 0 - client disconnect without sending a type\n"); if(type == 1){ // A report of squirrels uint32_t reported_squirrels; // same as "unsigned" or "unsigned int" read(client_fd, &reported_squirrels, 4); squirrel_count += reported_squirrels; type = 3; write(client_fd, &type, 1); printf("New squirrel count is %d\n", squirrel_count); } else if(type == 2) { // A query for the total type = 4; write(client_fd, &type, 1); write(client_fd, &squirrel_count, 4); } else { printf("Client sent us type %d\n", type); } close(client_fd); } return 0; }