#ifndef unix
#include <winsock2.h>
#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>
#endif
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define PORT 1200
#define QLEN 3
int main()
{
struct protoent *ptrp;
struct sockaddr_in sad;
struct sockaddr_in cad;
SOCKET sd, sd2;
int alen;
#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));
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = INADDR_ANY;
sad.sin_port = htons((u_short)PORT);
ptrp = getprotobyname("tcp");
if ( ptrp == 0) {
cerr << "cannot map \"tcp\" to protocol number" << endl;
exit(1);
}
sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
if (sd < 0) {
cerr << "socket creation failed" << endl;
exit(1);
}
if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
cerr << "bind failed" << endl;
exit(1);
}
if (listen(sd, QLEN) < 0) {
cerr << "listen failed" << endl;
exit(1);
}
{
char buf[1000];
int visits = 0;
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();
#endif
return(0);
}