Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <string.h>
- #include <malloc.h>
- #include <errno.h>
- #include <stdlib.h>
- #define PORT 8080
- #define N_CON 5
- #define BUF_LEN 6
- void custom_bind() {
- int sockfd, newsockfd, portno, clilen;
- struct sockaddr_in serv_addr, cli_addr;
- char buffer[BUF_LEN] = "";
- int counter = 0;
- sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (sockfd < 0) {
- perror("ERROR opening socket");
- exit(1);
- }
- bzero((char *) &serv_addr, sizeof(serv_addr));
- portno = PORT;
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- serv_addr.sin_port = htons((uint16_t) portno);
- if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
- perror("ERROR on binding");
- exit(1);
- }
- while(1) {
- listen(sockfd, N_CON);
- clilen = sizeof(cli_addr);
- newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, (socklen_t *) &clilen);
- if (newsockfd < 0) {
- perror("ERROR on accept");
- exit(1);
- }
- printf("New client connected\n");
- fflush(stdout);
- counter++;
- int n = (int) read(newsockfd, &buffer, BUF_LEN * sizeof(char));
- if (n < 0) {
- perror("ERROR reading from socket choice");
- exit(1);
- }
- printf("Command from client: %s\n", buffer);
- if (!strcmp(buffer, "count")) {
- printf("Clients processed: %d\n", counter);
- } else if (!strcmp(buffer, "date")) {
- system("date");
- }
- }
- shutdown(newsockfd, 2);
- }
- int main() {
- while (1) {
- custom_bind();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement