/* Test distributed server program. */ /* This program waits for a message on the port specified on the command line. When it receives a message, it replys to the sender. The program should be exected with the decimal port number on the comand line. */ /* PC = 1 if compiled under Microsoft C++ */ #define PC 0 #include <iostream.h> #include <stdlib.h> #include <sys/types.h> #include <stdio.h> #if PC #include <winsock.h> #define WINSOCK_VERSION 0x0101 /* Program requires Winsock version 1.1 */ #define NO_FLAGS 0 /* No special flags specified */ #else #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #endif /* size of input buffer */ #define INSIZE 128 /* maximum host name length */ #define MAXHOSTNAME 63 #if PC void main( ) { WSADATA wsaData; /* Windows socket initialization data */ #else void main(int argc, char *argv[]) { #endif struct hostent *h; /* getnamebyhost info returned */ struct sockaddr_in sa; /* socket address */ struct sockaddr_in fromaddr; /* client address */ int soxdes; /* socket descriptor */ short portnum; /* port number of server */ int addrlen; /* length of address */ int i; char *replay = "got it"; /* server reply */ char hostname[MAXHOSTNAME+1]; /* this host's name */ char inbuf[INSIZE]; /* input message buffer */ /* get the port number */ #if PC cout<<"Enter port number >"; cin>>portnum; #else portnum = atoi(argv[1]); #endif if (!portnum) { cout<< portnum <<"* is an invalid port number *\n"; exit(5); } #if PC if (WSAStartup(WINSOCK_VERSION, &wsaData)) { puts("* Error opening Winsock *"); exit(11); } #endif /* get the local host name and address */ gethostname( hostname, MAXHOSTNAME ); if((h = gethostbyname( hostname )) == NULL) { cout<<"cannot find host address "<< hostname; exit(7); } /* build socket address structure */ memcpy((char *)&sa.sin_addr, (char *)h->h_addr, h->h_length); sa.sin_family = h->h_addrtype; sa.sin_port = htons(portnum); cout<<"local host address\n"; cout<< h->h_name <<endl; cout<< inet_ntoa( sa.sin_addr ); /* allocate an open socket */ soxdes = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (soxdes == -1) { perror("socket"); exit(7); } cout<<"socket "<< soxdes <<" created/n"; /* bind the socket to the specified port */ if (bind( soxdes, (struct sockaddr *)&sa, sizeof sa) < 0) { perror("bind"); exit(5); } cout<<" and bound to port\n"<< ntohs(sa.sin_port); /* read a message */ addrlen = sizeof(fromaddr); if ((i = recvfrom(soxdes, inbuf, INSIZE, 0, (struct sockaddr *)&fromaddr, &addrlen)) <= 0) { perror("recvfrom"); exit(3); } inbuf[i] = (char)'/0'; cout<<"from\n"<< inbuf << inet_ntoa( fromaddr.sin_addr ); /* send a reply */ if ((sendto(soxdes, replay, strlen(replay)+1, 0, (struct sockaddr *)&fromaddr, addrlen)) < 0) { perror("sendto"); } /* close sockets and quit */ #if PC closesocket(soxdes); WSACleanup(); /* Free all allocated program resources */ #else close(soxdes); #endif puts("all done"); }