C/C++ Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
 
User Name:
Password:
Remember me
 
Go Back   Dev Articles Community ForumsProgrammingC/C++ Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Display Modes
 
Unread Dev Articles Community Forums Sponsor:
  #1  
Old April 28th, 2006, 02:59 AM
jaro jaro is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Nov 2005
Posts: 35 jaro User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 Day 6 h 16 m 44 sec
Reputation Power: 4
Send a message via Yahoo to jaro
Question How do I know if a server (on the box) is running?

Hi again,

Lately I'm doing socket programming, as far I can tell it works fine.
the problem is that how do I know if a server (on the box) is running.
The gethostbyname() will only detect if a IP address exist or is currently running.

The only idea that I have is, after gethostbyname() and a successful connect() my program will send some sort of message, then the (workspace)server will then send a valid response. If no valid response is recieve then the process will start all over again.

is this the way to go, just to know if a (workspace)server is running or there is another way ?

regards,
jaro

Reply With Quote
  #2  
Old May 1st, 2006, 03:46 PM
ubergeek ubergeek is offline
Contributing User
Dev Articles Novice (500 - 999 posts)
 
Join Date: Jan 2005
Posts: 600 ubergeek User rank is Private First Class (20 - 50 Reputation Level)ubergeek User rank is Private First Class (20 - 50 Reputation Level) 
Time spent in forums: 2 Days 22 h 40 m 27 sec
Reputation Power: 4
Send a message via AIM to ubergeek
well, if you can connect() to a server, it is running. If by "server" you mean a specific program, not the whole machine, then some kind of confirmation message (using a GUID or a password or something) is probably the best way to go.

Reply With Quote
  #3  
Old May 2nd, 2006, 11:56 AM
jaro jaro is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Nov 2005
Posts: 35 jaro User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 Day 6 h 16 m 44 sec
Reputation Power: 4
Send a message via Yahoo to jaro
Quote:
Originally Posted by ubergeek
well, if you can connect() to a server, it is running. If by "server" you mean a specific program, not the whole machine, then some kind of confirmation message (using a GUID or a password or something) is probably the best way to go.


Now what if, while the program is still connected to the server and by some wierd reason the server shuts down (i.e. power outage), how would I know if the server is still running?

I'm thinking of doing a connect() from time to time to check if the connection is still fine.If connect() returns other than "socket is still connected" (WSAEISCONN) then
the program will try to reconnect and will continue to do so until it is connected again.


is this the logical way to go? or there is another way ?

Reply With Quote
  #4  
Old May 2nd, 2006, 03:54 PM
ubergeek ubergeek is offline
Contributing User
Dev Articles Novice (500 - 999 posts)
 
Join Date: Jan 2005
Posts: 600 ubergeek User rank is Private First Class (20 - 50 Reputation Level)ubergeek User rank is Private First Class (20 - 50 Reputation Level) 
Time spent in forums: 2 Days 22 h 40 m 27 sec
Reputation Power: 4
Send a message via AIM to ubergeek
Well presumably if you are maintaining the socket you are send()ing and recv()ing with it, and you know to stop using it when those return an error code indicating a broken connection like WSAEINTR (has been closed), WSAENOTCONN (not connected), WSAENETRESET (kepp-alive service failed and broke connection), WSAESHUTDOWN (the socket was shutdown() peacefully), WSAECONNABORTED (something died and the connection was broken), WSAETIMEDOUT (the network died or the other computer stopped responding), or WSAECONNRESET (something died on the remote computer and broke the connection).

If you are not regularly reading or writing to the socket (but then what would be the point of maintaining the connection) then the connect() approach might be best.
You could also use select() and put your socket in the list of sockets to check for errors (for this approach you'd probably also want to make that call to select() nonblocking).

HTH, ubergeek

Reply With Quote
  #5  
Old May 12th, 2006, 06:55 AM
jaro jaro is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Nov 2005
Posts: 35 jaro User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 Day 6 h 16 m 44 sec
Reputation Power: 4
Send a message via Yahoo to jaro
Ok.I realize that doing a connect() from time to time to check if the connection is not really the way to go and also waste resources.
I did some changes in the codes ,following ubergeek advice,and the result is written below. Also ubergeek advice to use select(),but these pass weeks I have been busy and I haven't read yet on how to use select().


Code:
#include <stdio.h>
#include <winsock.h> 

#define STRSIZE 16536

void handle_error(void);
void receiveMessage(void);
void connectToWorkSpace();


char recvbuf[60000] = "";
SOCKET ConnectSocket;
struct sockaddr_in clientService; 

int bytesSent;
int bytesRecv = 0;
char sendbuf[500] = "";
 
struct hostent *h; 
char HOSTNME[20]="";
char hostname[20] = "localhost";			// for testing purposes
char hostnamebackup[20] = "local-blahblah";	// for testing purposes

int chker=0;

int main() 
{
	connectToWorkSpace();		
		
		while(1){
			receiveMessage();
		}


}


void receiveMessage()
{
	int bytesRecv = 0;


	bytesRecv = recv( ConnectSocket, recvbuf, 60000, 0 );

	
	if (bytesRecv == 0 ||  
		bytesRecv == SOCKET_ERROR ||
		WSAGetLastError() == WSAEINTR ||		/*(has been closed)*/
		WSAGetLastError() == WSAENOTCONN ||		/*(not connected)*/
		WSAGetLastError() == WSAENETRESET ||	/*(kepp-alive service failed and broke connection)*/
		WSAGetLastError() == WSAESHUTDOWN ||	/*(the socket was shutdown() peacefully)*/
		WSAGetLastError() == WSAECONNABORTED ||	/*(something died and the connection was broken)*/
		WSAGetLastError() == WSAETIMEDOUT ||	/*(the network died or the other computer stopped responding)*/
		WSAGetLastError() == WSAECONNRESET		/*(something died on the remote computer and broke the connection)*/
		){
			printf("Reconnect!\n");
			connectToWorkSpace();
	}else{
		recvbuf[bytesRecv]='\0';
			if(strlen(recvbuf)>0){
				printf("received message: %s \n", recvbuf);
			}
	}

}



void connectToWorkSpace()
{

int chkHost=0;
int loopHost=0;
int conn = 1;

	WSADATA wsaData;
	WORD wVersionRequested;               
	wVersionRequested = MAKEWORD( 1, 1 );


	if ( WSAStartup( wVersionRequested, &wsaData ) != 0 ){
		fprintf(stderr,"WSAStartup Error..."); 
		handle_error();
	}

	// will loop until connect() is successful
	while(conn != 0){

		chkHost =chker%2;

		if(chkHost == 0){
			printf("Connect Using Primary Host\n");
			strcpy(HOSTNME,hostname);
		}
		else {
			printf("Connect Using Backup Host\n");
			strcpy(HOSTNME,hostnamebackup);
		}

		// will loop until HOSTNME is reachable
		while(loopHost==0){
			chkHost =chker%2;
			if((h=gethostbyname(HOSTNME))==NULL)
			{ 
					printf("%s not reachable\n",HOSTNME);
					
					if(chkHost == 1){
						printf("Connect Using Primary Host\n");
						strcpy(HOSTNME,hostname);
					}
					else {
						printf("Connect Using Backup Host\n");
						strcpy(HOSTNME,hostnamebackup);
					}
					
			}else{
				loopHost=1;
			}
			Sleep(1000);
			chker++;
		}

			

		clientService.sin_addr=*((struct in_addr*)h->h_addr); 
		clientService.sin_port = htons(8770);
		clientService.sin_family = AF_INET;


			
		// Create a SOCKET for connecting to server
		ConnectSocket = socket(AF_INET, SOCK_STREAM, 0);
		if (ConnectSocket == -1) {
			handle_error();
			printf("Error at socket(): \n");
			//return -1;
		}

		// Connect 
		if( connect( ConnectSocket, (struct sockaddr*) &clientService, sizeof(struct sockaddr) ) == -1) {
			printf("Failed to connect. Workspaceserver is down.\n" );
			printf("Reconnecting........\n" );										
			loopHost=0;
			Sleep(5000);	
			conn = 1;
		}
		else {
			conn = 0;
			printf("Connection Success!\n");
		}

	}

	strcpy(sendbuf,"jaro");
	strcat(sendbuf, " :username");
	strcat(sendbuf, "\n");

	/* Send */
	bytesSent = send( ConnectSocket, sendbuf, strlen(sendbuf), 0 );
	printf( "\n messages Sent: %s\n", sendbuf );				
}


void handle_error(void)
{
  /*
   * Errors are handled by calling the WSAGetLastError routine which 
   * will return the last error as one of the following. As we develop
   * this tutorial, we will go into much more detail on what they mean
   * and what caused them.
   */
	int x;
	x= WSAGetLastError();

  switch ( x )
  {
    case WSANOTINITIALISED :
      printf("Unable to initialise socket.\n");
    break;
    case WSAEAFNOSUPPORT :
      printf("The specified address family is not supported.\n");
    break;
    case WSAEADDRNOTAVAIL :
      printf("Specified address is not available from the local machine.\n");
    break;
    case WSAECONNREFUSED :
      printf("The attempt to connect was forcefully rejected.\n"); 
      break; 
    case WSAEDESTADDRREQ : 
      printf("address destination address is required.\n");
    break;
    case WSAEFAULT :
      printf("The namelen argument is incorrect.\n");
    break;
    case WSAEINVAL :
      printf("The socket is not already bound to an address.\n");
    break;
    case WSAEISCONN :
      printf("The socket is already connected.\n");
    break;
    case WSAEADDRINUSE :
      printf("The specified address is already in use.\n");
    break;
    case WSAEMFILE : 
      printf("No more file descriptors are available.\n");
    break;
    case WSAENOBUFS :
      printf("No buffer space available. The socket cannot be created.\n");
    break;
    case WSAEPROTONOSUPPORT :
      printf("The specified protocol is not supported.\n");
      break; 
    case WSAEPROTOTYPE :
      printf("The specified protocol is the wrong type for this socket.\n");
    break;
    case WSAENETUNREACH : 
      printf("The network can't be reached from this host at this time.\n");
    break; 
    case WSAENOTSOCK :
       printf("The descriptor is not a socket.\n");
    break;
    case WSAETIMEDOUT :
      printf("Attempt timed out without establishing a connection.\n");
    break;
    case WSAESOCKTNOSUPPORT :
       printf("Socket type is not supported in this address family.\n");
    break;
    case WSAENETDOWN :
      printf("Network subsystem failure.\n");
    break;
    case WSAHOST_NOT_FOUND :
      printf("Authoritative Answer Host not found.\n");
    break;
    case WSATRY_AGAIN :
      printf("Non-Authoritative Host not found or SERVERFAIL.\n");
     break;
    case WSANO_RECOVERY :
       printf("Non recoverable errors, FORMERR, REFUSED, NOTIMP.\n");
    break;
    case WSANO_DATA :
      printf("Valid name, no data record of requested type.\n");
    break;
      case WSAEINPROGRESS :
      printf("address blocking Windows Sockets operation is in progress.\n");
    break;
    case WSAEINTR :
      printf("The (blocking) call was canceled via WSACancelBlockingCall().\n");
    break;
    default :
      printf("Unknown error.\n");
     break;
  }

}


Just need some comment (good or bad) on the program that I've written. Just need to know if I'm on the right track.

regards,
jaro

Reply With Quote
  #6  
Old May 12th, 2006, 06:01 PM
ubergeek ubergeek is offline
Contributing User
Dev Articles Novice (500 - 999 posts)
 
Join Date: Jan 2005
Posts: 600 ubergeek User rank is Private First Class (20 - 50 Reputation Level)ubergeek User rank is Private First Class (20 - 50 Reputation Level) 
Time spent in forums: 2 Days 22 h 40 m 27 sec
Reputation Power: 4
Send a message via AIM to ubergeek
looks pretty good. Just one thing, in the receiveMessage function, you might want to call WSAGetLastError() once and store the result in a variable, then compare against the variable, to avoid the overhead of calling the API function so many times.

Reply With Quote
Reply

Viewing: Dev Articles Community ForumsProgrammingC/C++ Help > How do I know if a server (on the box) is running?


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump



 Free IT White Papers!
 
How to Present Effectively Online
This white paper offers practical and actionable advice on the key steps that any presenter should consider as they plan and execute a Webinar or online meeting.

Request Your Free Technology Downloads!
 
Open Source Security Myths
Open Source Software (OSS) is computer software whose source code is available to the general public with relaxed or non-existent intellectual property restrictions (or arrangement such as the public domain), and is usually developed with the input of many contributors.

Request Your Free Technology Downloads!
 
Power and Cooling Capacity Management for Data Centers
This paper describes the principles for achieving power and cooling capacity management.

Request Your Free Technology Downloads!
 
Scalable, Fault-Tolerant NAS for Oracle - The Next Generation
For several years NAS has been evolving as a storage alternative for Oracle databases, and for good reason: NAS is quite often the simplest, most cost-effective storage approach for Oracle. Learn about the benefits that HP's approach to scalable NAS brings to Oracle environments in this comprehensive white paper.

Request Your Free Technology Downloads!
 
Understanding Web Application Security Challenges
This white paper discusses many common threats and preventive measures for Web application security, and explains what you can do to help protect your organization.

Request Your Free Technology Downloads!
 

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 





© 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
Stay green...Green IT