*BSD News Article 26069


Return to BSD News archive

Newsgroups: comp.unix.bsd
Path: sserve!newshost.anu.edu.au!munnari.oz.au!news.Hawaii.Edu!uhunix.uhcc.Hawaii.Edu!newsham
From: newsham@uhunix.uhcc.Hawaii.Edu (Tim Newsham)
Subject: select on non-blocking open
Message-ID: <CJptvz.GIu@news.Hawaii.Edu>
Sender: news@news.Hawaii.Edu
Organization: University of Hawaii
Date: Sun, 16 Jan 1994 09:19:10 GMT
Lines: 85


Hi,
  I am trying to open a socket in non-blocking mode so it
returns right away and later test if the connection has been
made.  On HP-UX 'connect()' man page it says if the socket
is O_NDELAY then you select for writing to test if a connection
has been made.  The man pages on sunos are not so clear but
seem to imply you should select for writing as well.  I have
tried the following program,  it tries two connections, the
first should pass and the second should fail.  This works fine
on HP-UX 8.0 and Solaris (dunno version) but fails under both
SunOS4.1.3 and Ultrix (dunno version).  It appears that the
two BSD machines behave identically.  What is the proper way
for doing this?  

--- test3.c -----


/* test socket in non-blocking w/ connect() and select() */

#define ADDR   "128.171.60.1"   /* change me */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>

int done=0;

handler(i)
int i;
{
  done=1;
  printf("Got signal\n");
}

try(port)
int port;
{
  struct sockaddr_in a;
  struct fd_set wr;
  int s;

  a.sin_family= AF_INET;
  a.sin_addr.s_addr = inet_addr(ADDR);
  a.sin_port = htons(port);
  s = socket(AF_INET,SOCK_STREAM,0);
  if(s<0) {
    perror("socket");
    return;
  }

  if(fcntl(s,F_SETFL,O_NDELAY)<0) {
     perror("fcntl");
     return;
  }
  
  if(connect(s,&a,sizeof(a)) < 0) {
      perror("connect");
     /* return; */
  }
  signal(SIGALRM,handler);
  alarm(5);

  FD_SET(s,&wr);
  if(select(32,0,&wr,0,0) < 0) {
     perror("select");
     return;
  } else {
    if(FD_ISSET(s,&wr)) 
      printf("Connected to %d\n",port);
  }
  alarm(0);
  close(s);
}

main()
{
  try(23);
  try(12345);
  printf("done.\n");
}