Skip to content

Instantly share code, notes, and snippets.

@jorben
Created December 2, 2015 01:43
Show Gist options
  • Save jorben/96a87df87f6c5b89f8a4 to your computer and use it in GitHub Desktop.
Save jorben/96a87df87f6c5b89f8a4 to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#define MAXLINE 1024
void handle(int conn_fd);
int main(int argc, char **argv)
{
int listen_fd, conn_fd;
int server_port = 53101;
int listen_q = 1024;
pid_t child_pid;
socklen_t socklen;
struct sockaddr_in cli_addr, serv_addr;
socklen = sizeof(cli_addr);
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(server_port);
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if(0 > listen_fd)
{
perror("socket error");
return listen_fd;
}
if(0 > bind(listen_fd, (struct sockaddr *) &serv_addr, socklen))
{
perror("bind error");
return -1;
}
if(0 > listen(listen_fd, listen_q))
{
perror("listen error");
return -1;
}
printf("server startup, listen on port:%d\n", server_port);
for( ; ; )
{
conn_fd = accept(listen_fd, (struct sockaddr *) &cli_addr, &socklen);
if(0 > conn_fd)
{
perror("accept error");
continue;
}
// sprintf(buf, "accept from %s:%d\n", inet_ntoa(cli_addr.sin_addr), cli_addr.sin_port);
printf("accept from %s:%d\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
child_pid = fork();
if(0 == child_pid)
{
// child process
close(listen_fd);
handle(conn_fd);
exit(0);
}
else if (0 < child_pid)
{
// parent process
close(conn_fd);
}
else
{
perror("fork error");
}
}
if (listen_fd)
{
close(listen_fd);
}
return 0;
}
void handle(int conn_fd)
{
size_t n;
char buf[MAXLINE];
for( ; ; )
{
n = read(conn_fd, buf, MAXLINE);
if(0 > n)
{
if(EINTR != errno)
{
perror("read error");
break;
}
}
if(0 == n)
{
close(conn_fd);
printf("client quit\n");
break;
}
if(0 == strncmp("exit", buf, 4))
{
close(conn_fd);
printf("client offline\n");
break;
}
write(conn_fd, buf, n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment