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

BOOL PSTUNClient::CreateSocket ( PUDPSocket *&  socket  ) 

Create a single socket. The STUN protocol is used to create a socket for which the external IP address and port numbers are known. A PUDPSocket descendant is returned which will, in response to GetLocalAddress() return the externally visible IP and port rather than the local machines IP and socket.

The will create a new socket pointer. It is up to the caller to make sure the socket is deleted to avoid memory leaks.

The socket pointer is set to NULL if the function fails and returns FALSE.

Definition at line 642 of file pstun.cxx.

References PSTUNUDPSocket::externalIP, GetNatType(), GetNatTypeName(), PSocket::port, PChannel::SetReadTimeout(), and PUDPSocket::SetSendAddress().

{
  socket = NULL;

  switch (GetNatType(FALSE)) {
    case ConeNat :
    case RestrictedNat :
    case PortRestrictedNat :
      break;

    case SymmetricNat :
      if (singlePortInfo.basePort == 0 || singlePortInfo.basePort > singlePortInfo.maxPort)
      {
        PTRACE(1, "STUN\tInvalid local UDP port range "
               << singlePortInfo.currentPort << '-' << singlePortInfo.maxPort);
        return FALSE;
      }
      break;

    default : // UnknownNet, SymmetricFirewall, BlockedNat
      PTRACE(1, "STUN\tCannot create socket using NAT type " << GetNatTypeName());
      return FALSE;
  }

  PSTUNUDPSocket * stunSocket = new PSTUNUDPSocket;
  if (OpenSocket(*stunSocket, singlePortInfo))
  {
    PSTUNMessage request(PSTUNMessage::BindingRequest);
    request.AddAttribute(PSTUNChangeRequest(false, false));
    PSTUNMessage response;

    if (response.Poll(*stunSocket, request, pollRetries))
    {
      PSTUNMappedAddress * mappedAddress = (PSTUNMappedAddress *)response.FindAttribute(PSTUNAttribute::MAPPED_ADDRESS);
      if (mappedAddress != NULL)
      {
        stunSocket->externalIP = mappedAddress->GetIP();
        if (GetNatType(FALSE) != SymmetricNat)
          stunSocket->port = mappedAddress->port;
        stunSocket->SetSendAddress(0, 0);
        stunSocket->SetReadTimeout(PMaxTimeInterval);
        socket = stunSocket;
        return true;
      }

      PTRACE(2, "STUN\tExpected mapped address attribute from server " << serverAddress << ':' << serverPort);
    }
    else
      PTRACE(1, "STUN\tServer " << serverAddress << ':' << serverPort << " unexpectedly went offline.");
  }

  delete stunSocket;
  return false;
}


Generated by  Doxygen 1.6.0   Back to index