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 GetNatType(), GetNatTypeName(), PSocket::port, PChannel::SetReadTimeout(), and PUDPSocket::SetSendAddress().

Referenced by StunClient::Main().

  socket = NULL;

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

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

    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);
        socket = stunSocket;
        return true;

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

  delete stunSocket;
  return false;

Here is the call graph for this function:

Here is the caller graph for this function:

Generated by  Doxygen 1.6.0   Back to index