/* * server.c - code for example server program that uses TCP * */

#ifndef unix #include <winsock2.h> /* also include Ws2_32.lib library in linking opitons */ #else #define closesocket close #define SOCKET int #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> /* also include xnet library for linking; on command line add: -lxnet */ #endif #include <iostream> #include <cstdio> /* necessary to get sprintf */ #include <cstring> using namespace std; #define PORT 1200 /* default protocol port number */ #define QLEN 3 /* size of request queue */ /*------------------------------------------------------------------------ * Program: server * * Purpose: allocate a socket and then repeatedly execute the following: * (1) wait for the next connection from a client * (2) send a short message to the client * (3) close the connection * (4) go back to step (1) * *------------------------------------------------------------------------ */ int main() { struct protoent *ptrp; /* pointer to a protocol table entry */ struct sockaddr_in sad; /* structure to hold server's address */ struct sockaddr_in cad; /* structure to hold client's address */ SOCKET sd, sd2; /* socket descriptors - integers */ int alen; /* length of address */ #ifdef WIN32 WSADATA wsaData; if(WSAStartup(0x0101, &wsaData)!=0) { fprintf(stderr, "Windows Socket Init failed: %d\n", GetLastError()); exit(1); } #endif memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */ sad.sin_family = AF_INET; /* set family to Internet */ sad.sin_addr.s_addr = INADDR_ANY; /* set the local IP address */ sad.sin_port = htons((u_short)PORT);/* use the defined port num */ /* Map TCP transport protocol name to protocol number */ ptrp = getprotobyname("tcp"); if ( ptrp == 0) { cerr << "cannot map \"tcp\" to protocol number" << endl; exit(1); } /* Create a socket */ sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto); if (sd < 0) { cerr << "socket creation failed" << endl; exit(1); } /* Bind a local address to the socket */ if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) { cerr << "bind failed" << endl; exit(1); } /* Specify size of request queue */ if (listen(sd, QLEN) < 0) { cerr << "listen failed" << endl; exit(1); } { char buf[1000]; /* buffer for string the server sends */ int visits = 0; /* counts client connections */ /* Main server loop - accept and handle requests */ while (1) { alen = sizeof(cad); sd2=accept(sd, (struct sockaddr *)&cad, &alen); if ( sd2<0) { cerr << "accept failed" << endl; exit(1); } visits++; sprintf(buf,"This server has been contacted %d time%s\n", visits,visits==1?".":"s."); send(sd2,buf,strlen(buf),0); closesocket(sd2); } } #ifdef WIN32 WSACleanup(); /* releaseuse of winsock.dll */ #endif return(0); }