#include
"w_main.h"
/**
* File Name: w_server.cpp
* Author : Edison
Chindrawaly
* Course : CSCI 4330 TCP/IP Fall 2001
* Desc
: It sends report to w_client regarding the
*
current load of the CSP server through
* TCP's connection.
* Usage
: ./w_server 1080
*/
char*
performCheck(char *);
char* strtrim(char*);
void main(int argc,
char *argv[])
{
int
s,so;
struct sockaddr_in
server;
int port =
atoi(argv[1]);
int n_bytes;
char rmessage[MAXSIZE];
char store[MAXSIZE];
if((so=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == ERROR)
cerr<<"Error in opening
socket"<<endl;
memset(&server,0,sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons((unsigned
short)port);
server.sin_addr.s_addr = INADDR_ANY;
if(bind(so,(struct sockaddr
*)&server,sizeof(server)) == ERROR)
{
cerr<<"Error in bind"<<endl;
exit(0);
}
if(listen(so,5) == ERROR)
cerr<<"Error in listen"<<endl;
if((s=accept(so,(struct sockaddr
*)&server,
(socklen_t *)sizeof(server))) == ERROR)
cerr<<"Error in accept"<<endl;
char* sign = performCheck(store);
if(sign != NULL)
strcpy(rmessage,store);
if((n_bytes=send(s,rmessage,sizeof(rmessage),0)) == ERROR)
cerr<<"Error in
send"<<endl;
}
/**
* performCheck(): To do the reporting of the current
* load balance of the server.
* @param
char* store - variable that stores
* @return char* the current load - else NULL if error occurs
*/
char* performCheck(char* store)
{
int maxlength = 256;
FILE *fpin;
char buffer[maxlength];
char *token, *strpos;
char cmd[2] = "w";
bool flag;
if((fpin
= popen(cmd,"r")) == NULL)
return NULL;
while(fgets(buffer, maxlength, fpin) != NULL)
{
flag = false;
strpos =
buffer;
while((token=strsep(&strpos,":"))!=NULL)
{
if(flag == true)
{
strtrim(token);
strcpy(store,token);
return store;
}
if(strstr(token,"average") != NULL)
flag = true;
}
}
return NULL;
}
/**
* strtrim(): To delete the leading blank
space of the string.
* Courtesy of DonR (lecture of UNT
CSCI)
* @param char* string - to be trim
* @return char* string - else NULL if
error
*/
char* strtrim(char
*s)
{
if(s == NULL)
return NULL;
char *p = s;
while(*p == ' ')
p++;
strcpy(s,p);
p = s + strlen(s)-1;
while(p >= s && *p == ' ')
*p-- = '\0';
return s;
}