04-27-06 12:55 PM
Yes it is accept that is blocking and will not unblock...
Maybe there is a sock option I can set so that accept will time out...
#include <iostream>
#include <stdio.h> /* standard I/O functions
*/
#include <unistd.h> /* standard unix functions, like alarm()
*/
#include <signal.h> /* signal name macros, and the signal()
prototype */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <strings.h>
#include <netdb.h>
int m_nSocketFD;
int m_nPortNo;
struct sockaddr_in serv_addr;
void Open(int nPort)
{
m_nPortNo = nPort;
m_nSocketFD = (int)socket(AF_INET, SOCK_STREAM, 0);
if (m_nSocketFD < 0)
{
throw("ERROR opening socket");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(m_nPortNo);
int x = 1;
if (setsockopt(m_nSocketFD, SOL_SOCKET, SO_REUSEADDR, (char *)&x,
sizeof x) == -1)
throw("setsockopt SO_REUSEADDR failed");
if (bind(m_nSocketFD, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
{
throw("ERROR on binding");
}
}
int Listen(void)
{
listen(m_nSocketFD, 5);
struct sockaddr_in cli_addr;
socklen_t clilen = sizeof(cli_addr);
int newsockfd = (int)accept(m_nSocketFD, (struct sockaddr *)
&cli_addr, &clilen);
if (newsockfd < 0)
{
throw("ERROR on accept");
}
return(newsockfd);
}
/* define an alarm signal handler. */
void catch_alarm(int sig_num)
{
printf("Operation timed out. Exiting...\n\n");
exit(0);
}
int main(int argc, char* argv[])
{
try
{
/* set a signal handler for ALRM signals */
signal(SIGALRM, catch_alarm);
/* prompt the user for input */
printf("Listening!");
fflush(stdout);
/* start a 30 seconds alarm */
alarm(30);
/* wait for user input */
Open(4096);
int resp=Listen();
/* remove the timer, now that we've got the user's input */
alarm(0);
}
catch(const char *msg)
{
printf("%s\n", msg);
}
return 0;
}
[ Post a follow-up to this message ]
|