Last active
March 17, 2016 10:07
-
-
Save maxking/bd8ff3947ee8fe7d6352 to your computer and use it in GitHub Desktop.
simple echo server demonstration
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> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
void dostuff(int); | |
void error(char *msg) | |
{ | |
perror(msg); | |
exit(1); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int sockfd, newsockfd, portno, clilen, pid, optval; | |
struct sockaddr_in serv_addr, cli_addr; | |
if(argc < 2) { | |
fprintf(stderr, "Error, no port provided\n"); | |
exit(1); | |
} | |
sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
optval = 1; | |
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); | |
if (sockfd < 0) { | |
error("Error opening socket"); | |
} | |
bzero((char *) &serv_addr, sizeof(serv_addr)); | |
portno = atoi(argv[1]); | |
serv_addr.sin_family = AF_INET; | |
serv_addr.sin_port = htons(portno); | |
serv_addr.sin_addr.s_addr = INADDR_ANY; | |
if (bind(sockfd, (struct sockaddr *) &serv_addr, | |
sizeof(serv_addr)) < 0) | |
error("Error on binding"); | |
listen(sockfd, 5); | |
clilen = sizeof(cli_addr); | |
while(1) { | |
newsockfd = accept(sockfd, | |
(struct sockaddr *) &cli_addr, &clilen); | |
if (newsockfd < 0) | |
error("Error on accept"); | |
pid = fork(); | |
if (pid < 0) | |
error("Error on fork"); | |
if (pid == 0) { | |
close(sockfd); | |
dostuff(newsockfd); | |
exit(0); | |
} | |
else | |
close(newsockfd); | |
} | |
return 0; | |
} | |
void dostuff(int newsockfd) { | |
int n; | |
char buffer[256]; | |
char exit[] = "exit"; | |
while(1) { | |
bzero(buffer, 256); | |
n = read(newsockfd, buffer, 255); | |
if (n < 0) | |
error("Error reading from socket"); | |
n = strcmp(buffer, exit); | |
if (n == 0) | |
break; | |
printf("Here is the message: %s\n", buffer); | |
n = write(newsockfd, "I got your message\n", 18); | |
if (n < 0) | |
error("Error writing to socket"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment