open a socket

hi all,
i meet a problem when opening a socket, is that when the remote host not available or its port hanged ,my program still suspending untill i cancel the operation...
but when the host is ok ,my program work ok.
i handled in my code all these exceptions ,but my problem is when the host is not avaialable i want to exit with that error ???!!!!
here is the part of my code for socket programming :


void ethernet::etherSetup(char *strIP,int nPort)
{
	unsigned long ip;
	
	if((*strIP <= '9') && (*strIP >= '0'))
		{
			if( (int)(ip = inet_addr(strIP)) == -1 )
				{
				printf("\r\nIP-address must be of the form a.b.c.d\n");
              	exit (2);
				}


		}
	else
		{
			server = gethostbyname(strIP);
    		if(!server) 
				{ 
				printf("\nError in host Name.\n");
				exit(2);
				}
   			ip = *(unsigned long*)(server->h_addr);
		}

/////printf("\r\nSERVER IP=%d\r\n ",ip);



	server = gethostbyaddr((char *)&ip,sizeof(ip),AF_INET);
	if (server == NULL)
		{
        	printf("\r\nERROR, no such host .\n");
        	exit(1);
    	}

	bzero((char *) &m_sockaddr_in, sizeof(m_sockaddr_in));

	m_sockaddr_in.sin_family = AF_INET;
	m_sockaddr_in.sin_port = htons(nPort);
	m_sockaddr_in.sin_addr = *(in_addr*)&ip;
	printf("remotehost : %s   , port : %d \n",strIP,nPort);
}

//-----------------------------------------------------------------
int ethernet::Create()
{
  sockfd = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
  if ( sockfd <0 ) return -1;
  return 0;
}
//-----------------------------------------------------------------
int ethernet::Connect()
{
	int ret;

  	ret = connect(sockfd,(sockaddr*)&m_sockaddr_in,sizeof(m_sockaddr_in));
  	if ( ret <0 ) return -1; //ERROR in connection>
  	return 0;
}



N.B:
this code runs under UNIX sun solaris OS
thanks.

By default socket calls are blocking. To make them non blocking, use setsockopt() with a receive timeout. or use ioctl with FIONBIO request.

-Dheeraj

Its also problematic in that sometimes hostname look up does take a few seconds, it has to give it time to look.

how can I use the functions setsockopt() and ioctl() in my code ???!!

take a look at man pages. Also stevens socket programming book is a very good reference.

thank you Gautamdheeraj I appreciate your help .
Is this book available and free on the internet ???

yes, its available over the internet. search ebookee.com for "UNIX Network Programming". You should get some link to download.