/*********************
|
* simple TCP-server *
|
*********************/
|
#include <fcntl.h>
|
#include <unistd.h>
|
#include <sys/socket.h>
|
#include <sys/types.h>
|
#include <stdlib.h>
|
#include <stdio.h>
|
#include <netdb.h>
|
#include <string.h>
|
|
int main(int argc, char **argv) {
|
unsigned short port; /* port to bind to */
|
char buffer[80]; /* i/o buffer */
|
struct sockaddr_in client; /* ip address of client */
|
struct sockaddr_in server; /* ip address of server */
|
struct hostent *hostnm; /* dest-hostname to connect to */
|
int s; /* socket */
|
int ns; /* socket connected to client */
|
int namelen; /* length of client name */
|
int optval=1;
|
int s_optlen=0;
|
ssize_t recvbytes; /* received bytes */
|
|
/* check for needed parameters */
|
if(argc!=3) {
|
fprintf(stderr, "%s portnumber\n", argv[0]);
|
exit(1);
|
}
|
hostnm=gethostbyname(argv[1]);
|
|
/* port to int */
|
port=(unsigned short) atoi(argv[2]);
|
|
/* generating socket */
|
if((s=socket(AF_INET, SOCK_STREAM,0))<0){
|
perror("Error:");
|
exit(2);
|
}
|
|
/* set socket options so that we can reuse the port */
|
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, s_optlen);
|
|
/* bind to socket */
|
server.sin_family = AF_INET;
|
server.sin_port = htons(port);
|
server.sin_addr.s_addr = *((unsigned long *)hostnm->h_addr);
|
|
if(bind(s, (struct sockaddr *)&server, sizeof(server))<0){
|
perror("Error:");
|
exit(3);
|
}
|
|
/* waiting for connections */
|
if(listen(s,1)!=0){
|
perror("Error:");
|
exit(4);
|
}
|
|
/* get connection */
|
namelen=sizeof(client);
|
|
/* we loop forever here to avoid stopping the server */
|
while(1) {
|
if((ns=accept(s, (struct sockaddr *)&client, &namelen))==-1){
|
perror("Error:");
|
exit(5);
|
}
|
|
/* write welcome banner to user */
|
snprintf(buffer, 54, "Welcome to the echo server, type a single x to quit.\n");
|
send(ns, buffer, 54, 0);
|
/* loop until we get an x as first char */
|
do {
|
/* get messages */
|
recvbytes=recv(ns, buffer, sizeof(buffer), 0);
|
if(recvbytes == -1){
|
perror("Error:");
|
exit(6);
|
}
|
|
/* send answer */
|
if(send(ns, buffer, recvbytes, 0) <0){
|
perror("Error:");
|
exit(7);
|
}
|
} while (buffer[0] != 'x');
|
|
/* client session closed on request, say bye bye */
|
snprintf(buffer, 30, "Good bye, see you next time.\n");
|
send(ns, buffer, 30, 0);
|
|
/* close connection */
|
close(ns);
|
}
|
|
/* close listener */
|
close(s);
|
printf("server exiting\n");
|
return(0);
|
}
|