dhilst

TCP Server Hello World example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netdb.h>

#define pexit(s) ({perror(s); exit(EXIT_FAILURE);})

#define BUFLEN 0x400
static char buf[BUFLEN];

int main(int argc, char **argv)
{
int srv_sock;
int cli_sock;
int srv_addr_len;
int cli_addr_len;
int error;
int nbytes;
struct sockaddr_in srv_addr;
struct sockaddr_in cli_addr;


if (argc <= 1) {
printf("Usage: %s PORT\n", argv[0]);
exit(EXIT_FAILURE);
}

srv_sock = socket(PF_INET, SOCK_STREAM, 0);
if (srv_sock < 0)
pexit("socket");


srv_addr_len = sizeof(srv_addr);
bzero(&srv_addr, srv_addr_len);
srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
srv_addr.sin_family = PF_INET;
srv_addr.sin_port = htons(atoi(argv[1]));

error = bind(srv_sock, (struct sockaddr *)&srv_addr, srv_addr_len);
if (error)
pexit("bind");

error = listen(srv_sock, 5);
if (error)
pexit("listen");

cli_addr_len = sizeof(cli_addr);
while ((cli_sock = accept(srv_sock, (struct sockaddr *)&cli_addr,
&cli_addr_len)) != -1)
{
printf("Received connection from %s\n",
inet_ntoa(cli_addr.sin_addr.s_addr));

nbytes = send(cli_sock, "Hello World\n", strlen("Hello World\n"), 0);
if (nbytes == -1)
perror("send");
close(cli_sock);
}

close(srv_sock);
return 0;
}