Logo Search packages:      
Sourcecode: pwlib version File versions  Download package

BOOL PIPSocket::Connect ( const Address iface,
WORD  localPort,
const Address addr 
) [virtual, inherited]

Parameters:
iface  Address of local interface to us.
localPort  Local port number for connection
addr  Address of remote machine to connect to.

Definition at line 1981 of file sockets.cxx.

References PChannel::Close(), PChannel::ConvertOSError(), PChannel::IsOpen(), PIPSocket::Address::IsValid(), PChannel::os_handle, and PSocket::SetOption().

{
  // close the port if it is already open
  if (IsOpen())
    Close();

  // make sure we have a port
  PAssert(port != 0, "Cannot connect socket without setting port");

#if P_HAS_IPV6

  Psockaddr sa(addr, port);

  // attempt to create a socket with the right family
  if (!OpenSocket(sa->sa_family))
    return FALSE;

  if (localPort != 0 || iface.IsValid()) {
    Psockaddr bind_sa(iface, localPort);

    if (!SetOption(SO_REUSEADDR, 0)) {
      os_close();
      return FALSE;
    }
    
    if (!ConvertOSError(::bind(os_handle, bind_sa, bind_sa.GetSize()))) {
      os_close();
      return FALSE;
    }
  }
  
  // attempt to connect
  if (os_connect(sa, sa.GetSize()))
    return TRUE;
  
#else

  // attempt to create a socket
  if (!OpenSocket())
    return FALSE;

  // attempt to connect
  sockaddr_in sin;
  if (localPort != 0 || iface.IsValid()) {
    if (!SetOption(SO_REUSEADDR, 0)) {
      os_close();
      return FALSE;
    }
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = iface;
    sin.sin_port        = htons(localPort);       // set the port
    if (!ConvertOSError(::bind(os_handle, (struct sockaddr*)&sin, sizeof(sin)))) {
      os_close();
      return FALSE;
    }
  }

  memset(&sin, 0, sizeof(sin));
  sin.sin_family = AF_INET;
  sin.sin_port   = htons(port);  // set the port
  sin.sin_addr   = addr;
  if (os_connect((struct sockaddr *)&sin, sizeof(sin)))
    return TRUE;

#endif

  os_close();
  return FALSE;
}


Generated by  Doxygen 1.6.0   Back to index