Skip to content

Instantly share code, notes, and snippets.

@cwgem
Last active August 29, 2015 14:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwgem/8d0a061707333e5ef3df to your computer and use it in GitHub Desktop.
Save cwgem/8d0a061707333e5ef3df to your computer and use it in GitHub Desktop.
C Echo Server (utilizing linux namespaces)
/*Required Headers*/
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sched.h>
#include <stdlib.h>
#include <sys/wait.h>
#define STACK_SIZE 1024*1024*5
void sig_handler(int signo)
{
if (signo == SIGINT)
exit(0);
}
int echo_server()
{
printf("Child: PID=%ld PPID=%ld\n", (long) getpid(), (long) getppid());
char str[100];
int listen_fd, comm_fd;
struct sockaddr_in servaddr;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
bzero( &servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
servaddr.sin_port = htons(7);
bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
setuid(65534);
signal(SIGINT, sig_handler);
listen(listen_fd, 10);
comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
bzero( str, 100);
read(comm_fd,str,100);
printf("Echoing back - %s",str);
write(comm_fd, str, strlen(str)+1);
return 0;
}
int main() {
char *stack;
char *stackTop;
stack = malloc(STACK_SIZE);
if (stack == NULL) {
printf("malloc(2) failed\n");
return 1;
}
signal(SIGCHLD, SIG_IGN);
stackTop = stack + STACK_SIZE;
pid_t child_pid = clone(echo_server, stackTop, CLONE_NEWPID | SIGCHLD, NULL);
waitpid(child_pid, NULL, 0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment