Simple c program that listens to some port and prints "Hello World" as responce
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 <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