Hier ist ein sehr einfacher TCP Echoserver unter Linux.
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
/* Puffer für eingehende Nachrichten */
#define RCVBUFSIZE 1024
int main( int argc, char *argv[]) {
struct sockaddr_in server, client;
int sock, fd;
unsigned int len;
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
memset( &server, 0, sizeof (server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(1234);
bind(sock,(struct sockaddr*)&server, sizeof( server));
listen(sock, 5);
/* endlosschleife (blocking) */
for (;;) {
len = sizeof(client);
fd = accept(sock, (struct sockaddr*)&client, &len);
if (fd < 0)
continue;
printf("Bearbeite den Client mit der Adresse: %s\n", inet_ntoa(client.sin_addr));
char echo_buffer[RCVBUFSIZE];
int recv_size;
recv_size = recv(fd, echo_buffer, RCVBUFSIZE,0);
echo_buffer[recv_size] = '\0';
printf("Nachrichten vom Client : %s", echo_buffer);
send(fd, echo_buffer, recv_size,0);
close(fd);
}
return 0;
}