      subroutine sock.connect.2(host, my.addr, sockfd, err)
*
*
*
*
*
*
*
*
*
*
$include ccall.common
$catalog local

      equate PF$INET to 2
      equate SOCK$STREAM to 1
      equate F$SETFL to 4
      equate O$NONBLOCK to 2048
      equate EAGAIN to 11
      
      err = ''

      host.name = field(host,':',1)
      host.port = field(host,':',2)
* display '[1]'
      call csub.gethostbyname(host.name,dummy1,dummy2,h.addrs)
      host.ip = h.addrs<1,1>
      if host.ip = '' then
         err = 'Host lookup failed.'
         return
      end
* display '[2]'

* There should probably be some more error checking
* here to handle bad host address or port specifications

      hst = ip2bin(host.ip)
* display '[3]'

      call csub.socket(PF$INET,SOCK$STREAM,0,sockfd)
      if sockfd < 0 then
         err = 'Error allocating socket'
         return
      end
* display '[4]'

      if my.addr <> '' then
         v1 = int2bin(2,2)

         v2 = int2bin(field(my.addr,':',2),2)
         v2 = h2n(v2)

         v3 = ip2bin(field(my.addr,':',1))

         addr = v1 : v2 : v3 : str(CC$NUL,16)
         addr = addr[1,16]

         call csub.bind(sockfd,addr,res)
         if res < 0 then
            err = 'Error setting socked local address - ' : cc$errno
            call csub.close(sockfd,'')
            return
         end
      end

* display '[5]'
      v1 = int2bin(2,2)

      v2 = int2bin(host.port,2)
      v2 = h2n(v2)

      v3 = ip2bin(host.ip)

      serv.addr = v1 : v2 : v3 : str(CC$NUL,16)
      serv.addr = serv.addr[1,16]

* display '[6]'
      call csub.connect(sockfd, serv.addr, res) 
      if res < 0 then
         err = 'Error calling connect - ' : cc$errno
         call csub.close(sockfd,'')
         return
      end

* display '[7]'
      call csub.fcntl3(sockfd, F$SETFL, O$NONBLOCK, res)
      if res < 0 then
         err = 'Error calling fcntl - ' : cc$errno
         call csub.close(sockfd,'')
         return
      end
* display '[8]'

      return
   end
