#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 PROTOPORT 1200
int main(int argc, char *argv[])
{
struct protoent *ptrp;
struct sockaddr_in sad;
struct sockaddr_in cad;
SOCKET sd;
int alen;
int port;
#ifdef WIN32
WSADATA wsaData;
if(WSAStartup(0x0101, &wsaData)!=0)
{
fprintf(stderr, "Windows Socket Init failed: %d\n", GetLastError());
exit(1);
}
#endif
if (argc > 1) {
port = atoi(argv[1]);
} else {
port = PROTOPORT;
}
if (port <= 0)
{
fprintf(stderr,"bad port number %s\n",argv[1]);
exit(1);
}
memset((char *)&sad,0,sizeof(sad));
sad.sin_port = htons((u_short)port);
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = INADDR_ANY;
ptrp = getprotobyname("udp");
if ( ptrp == 0) {
fprintf(stderr, "cannot map \"udp\" to protocol number");
exit(1);
}
sd = socket(PF_INET, SOCK_DGRAM, 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);
}
{
char buf[1000];
int visits = 0;
int n;
int m;
while (1) {
alen = sizeof(cad);
n = recvfrom(sd,buf,sizeof(buf),0,(struct sockaddr*)&cad,&alen);
if (n<0)
{
fprintf(stderr,"Error in receiving\n");
continue;
}
else if(n>=0)
{
visits++;
sprintf(buf,"This server has been contacted %d time%s\n",
visits,visits==1?".":"s.");
m = sendto(sd,buf,strlen(buf)+1,0,(struct sockaddr*)&cad,alen);
if(m<0)
{
fprintf(stderr,"Error in sending");
continue;
}
}
}
}
#ifdef WIN32
WSACleanup();
#endif
return(0);
}