Created
June 10, 2010 02:55
-
-
Save anr/432508 to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
#include <netinet/ip.h> | |
#include <arpa/inet.h> | |
#define BACKLOG 5 | |
#define BUF_SIZE 256 | |
void error(char *msg) | |
{ | |
perror(msg); | |
exit(EXIT_FAILURE); | |
} | |
int server_setup(void) | |
{ | |
int server_fd; | |
struct sockaddr_in server; | |
struct in_addr address; | |
int size = sizeof(server); | |
int opt = 1; | |
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { | |
error("Couldn't create socket"); | |
} | |
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) { | |
error("Couldn't set socket options"); | |
} | |
address.s_addr = INADDR_ANY; | |
server.sin_family = AF_INET; | |
server.sin_port = htons(1234); | |
server.sin_addr = address; | |
if (bind(server_fd, (struct sockaddr *) &server, (socklen_t) size) == -1) { | |
error("Couldn't bind socket"); | |
} | |
if (listen(server_fd, BACKLOG) == -1) { | |
error("Couldn't listen"); | |
} | |
return server_fd; | |
} | |
int accept_client(int server_fd) | |
{ | |
int client_fd; | |
struct sockaddr_in client; | |
int size = sizeof(client); | |
if ((client_fd = accept(server_fd, (struct sockaddr *) &client, (socklen_t *) &size)) == -1) { | |
error("Couldn't accept client"); | |
} | |
fprintf(stderr, "A client has arrived from %s port %d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); | |
return client_fd; | |
} | |
void handle_client(client_fd) | |
{ | |
char buffer[BUF_SIZE]; | |
int count; | |
char prefix[] = "You said: "; | |
char goodbye[] = "Goodbye!\r\n"; | |
while (1) { | |
count = read(client_fd, buffer, BUF_SIZE); | |
if (count == -1) { | |
perror("Bad read from client"); | |
return; | |
} | |
else if (count == 0) { | |
/* client closed the connection */ | |
close(client_fd); | |
} | |
buffer[count] = '\0'; | |
if (!strcmp(buffer, "quit\r\n")) { | |
write(client_fd, goodbye, strlen(goodbye)); | |
close(client_fd); | |
return; | |
} | |
write(client_fd, prefix, strlen(prefix)); | |
write(client_fd, buffer, count); | |
} | |
} | |
int main() | |
{ | |
int server_fd, client_fd; | |
server_fd = server_setup(); | |
while (1) { | |
client_fd = accept_client(server_fd); | |
handle_client(client_fd); | |
} | |
close(server_fd); | |
printf("Exiting...\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment