Skip to content

Instantly share code, notes, and snippets.

@wwwted
Created April 24, 2020 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wwwted/1f64a334d51640f124b2461e2dbe0b8c to your computer and use it in GitHub Desktop.
Save wwwted/1f64a334d51640f124b2461e2dbe0b8c to your computer and use it in GitHub Desktop.
Simple c program that listens to some port and prints "Hello World" as responce
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/*
Test application for k8s servies
Server that responds with HTTP result on specified port
Build: gcc -ohelloREST hello-listen.c
Run: ./helloREST 8001
Test by running: curl localhost:8001
Ted Wennmark 2019
*/
const char *reply =
"HTTP/1.1 200 OK\n"
"Content-Type: text/html\n"
"Content-Length: 12\n"
"Accept-Ranges: bytes\n"
"Connection: close\n"
"\n"
"Hello World!\n";
int print_usage(char * name)
{
fprintf(stderr,"ERROR: %s <port>\n", name);
}
void error(char *msg)
{
perror(msg);
exit(1);
}
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET)
return &(((struct sockaddr_in*)sa)->sin_addr);
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(int argc, char *argv[])
{
int port, my_sock, cli_sock, size;
struct sockaddr_in addr;
char s[INET6_ADDRSTRLEN];
if (argc != 2)
{
print_usage(argv[0]);
exit(1);
}
port=atoi(argv[1]);
my_sock = socket(PF_INET, SOCK_STREAM, 0);
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if(bind(my_sock, (struct sockaddr *) &addr, sizeof(addr))!=0)
{
error("ERROR on bind()\n");
}
if (listen(my_sock, 16)!=0)
{
error("ERROR on listen()\n");
}
size = sizeof(addr);
while ((cli_sock=accept(my_sock, (struct sockaddr *) &addr, &size)) > 0)
{
inet_ntop(addr.sin_family,
get_in_addr((struct sockaddr *)&addr),
s, sizeof s);
printf("Server: got connection from %s\n", s);
send(cli_sock, reply, strlen(reply), 0);
close(cli_sock);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment