SocketPermission Classe

Definição

Cuidado

Code Access Security is not supported or honored by the runtime.

Controla os direitos para estabelecer ou aceitar conexões em um endereço de transporte.Controls rights to make or accept connections on a transport address.

public ref class SocketPermission sealed : System::Security::CodeAccessPermission, System::Security::Permissions::IUnrestrictedPermission
public sealed class SocketPermission : System.Security.CodeAccessPermission, System.Security.Permissions.IUnrestrictedPermission
[System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public sealed class SocketPermission : System.Security.CodeAccessPermission, System.Security.Permissions.IUnrestrictedPermission
[System.Serializable]
public sealed class SocketPermission : System.Security.CodeAccessPermission, System.Security.Permissions.IUnrestrictedPermission
type SocketPermission = class
    inherit CodeAccessPermission
    interface IUnrestrictedPermission
[<System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
type SocketPermission = class
    inherit CodeAccessPermission
    interface IUnrestrictedPermission
[<System.Serializable>]
type SocketPermission = class
    inherit CodeAccessPermission
    interface IUnrestrictedPermission
Public NotInheritable Class SocketPermission
Inherits CodeAccessPermission
Implements IUnrestrictedPermission
Herança
SocketPermission
Atributos
Implementações

Exemplos

O exemplo a seguir demonstra como usar a SocketPermission classe para definir, alterar e impor várias restrições de acesso de soquete.The following example demonstrates how to use the SocketPermission class to set, change, and enforce various socket access restrictions.

// Creates a SocketPermission restricting access to and from all URIs.
SocketPermission^ mySocketPermission1 = gcnew SocketPermission( PermissionState::None );

// The socket to which this permission will apply will allow connections from www.contoso.com.
mySocketPermission1->AddPermission( NetworkAccess::Accept, TransportType::Tcp,  "www.contoso.com", 11000 );

// Creates a SocketPermission which will allow the target Socket to connect with www.southridgevideo.com.
SocketPermission^ mySocketPermission2 = gcnew SocketPermission( NetworkAccess::Connect,TransportType::Tcp, "www.southridgevideo.com",11002 );

// Creates a SocketPermission from the union of two SocketPermissions.
SocketPermission^ mySocketPermissionUnion =
   (SocketPermission^)( mySocketPermission1->Union( mySocketPermission2 ) );

// Checks to see if the union was successfully created by using the IsSubsetOf method.
if ( mySocketPermission1->IsSubsetOf( mySocketPermissionUnion ) &&
   mySocketPermission2->IsSubsetOf( mySocketPermissionUnion ) )
{
   Console::WriteLine(  "This union contains permissions from both mySocketPermission1 and mySocketPermission2" );
   
   // Prints the allowable accept URIs to the console.
   Console::WriteLine(  "This union accepts connections on :" );

   IEnumerator^ myEnumerator = mySocketPermissionUnion->AcceptList;
   while ( myEnumerator->MoveNext() )
   {
      Console::WriteLine( safe_cast<EndpointPermission^>( myEnumerator->Current )->ToString() );
   }
   
   // Prints the allowable connect URIs to the console.
   Console::WriteLine(  "This union permits connections to :" );

   myEnumerator = mySocketPermissionUnion->ConnectList;
   while ( myEnumerator->MoveNext() )
   {
      Console::WriteLine( safe_cast<EndpointPermission^>( myEnumerator->Current )->ToString() );
   }
}

// Creates a SocketPermission from the intersect of two SocketPermissions.
SocketPermission^ mySocketPermissionIntersect =
   (SocketPermission^)( mySocketPermission1->Intersect( mySocketPermissionUnion ) );

// mySocketPermissionIntersect should now contain the permissions of mySocketPermission1.
if ( mySocketPermission1->IsSubsetOf( mySocketPermissionIntersect ) )
{
   Console::WriteLine(  "This is expected" );
}

// mySocketPermissionIntersect should not contain the permissios of mySocketPermission2.
if ( mySocketPermission2->IsSubsetOf( mySocketPermissionIntersect ) )
{
   Console::WriteLine(  "This should not print" );
}

// Creates a copy of the intersect SocketPermission.
SocketPermission^ mySocketPermissionIntersectCopy =
   (SocketPermission^)( mySocketPermissionIntersect->Copy() );
if ( mySocketPermissionIntersectCopy->Equals( mySocketPermissionIntersect ) )
{
   Console::WriteLine(  "Copy successfull" );
}

// Converts a SocketPermission to XML format and then immediately converts it back to a SocketPermission.
mySocketPermission1->FromXml( mySocketPermission1->ToXml() );

// Checks to see if permission for this socket resource is unrestricted.  If it is, then there is no need to
// demand that permissions be enforced.
if ( mySocketPermissionUnion->IsUnrestricted() )
{
   //Do nothing.  There are no restrictions.
}
else
{
   // Enforces the permissions found in mySocketPermissionUnion on any Socket Resources used below this statement. 
   mySocketPermissionUnion->Demand();
}

IPHostEntry^ myIpHostEntry = Dns::Resolve(  "www.contoso.com" );
IPEndPoint^ myLocalEndPoint = gcnew IPEndPoint( myIpHostEntry->AddressList[ 0 ], 11000 );

Socket^ s = gcnew Socket( myLocalEndPoint->Address->AddressFamily,
   SocketType::Stream,
   ProtocolType::Tcp );
try
{
   s->Connect( myLocalEndPoint );
}
catch ( Exception^ e ) 
{
   Console::Write(  "Exception Thrown: " );
   Console::WriteLine( e->ToString() );
}

// Perform all socket operations in here.
s->Close();

     // Creates a SocketPermission restricting access to and from all URIs.
     SocketPermission mySocketPermission1 = new SocketPermission(PermissionState.None);

     // The socket to which this permission will apply will allow connections from www.contoso.com.
     mySocketPermission1.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "www.contoso.com", 11000);

     // Creates a SocketPermission which will allow the target Socket to connect with www.southridgevideo.com.
     SocketPermission mySocketPermission2 =
                                new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "www.southridgevideo.com", 11002);

     // Creates a SocketPermission from the union of two SocketPermissions.
     SocketPermission mySocketPermissionUnion =
                                (SocketPermission)mySocketPermission1.Union(mySocketPermission2);

     // Checks to see if the union was successfully created by using the IsSubsetOf method.
     if (mySocketPermission1.IsSubsetOf(mySocketPermissionUnion) &&
           mySocketPermission2.IsSubsetOf(mySocketPermissionUnion)){
          Console.WriteLine("This union contains permissions from both mySocketPermission1 and mySocketPermission2");

          // Prints the allowable accept URIs to the console.
          Console.WriteLine("This union accepts connections on :");

          IEnumerator myEnumerator = mySocketPermissionUnion.AcceptList;
       while (myEnumerator.MoveNext()) {
               Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
            }

             // Prints the allowable connect URIs to the console.
          Console.WriteLine("This union permits connections to :");

          myEnumerator = mySocketPermissionUnion.ConnectList;
       while (myEnumerator.MoveNext()) {
               Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
            }
           }


     // Creates a SocketPermission from the intersect of two SocketPermissions.
     SocketPermission mySocketPermissionIntersect =
                               (SocketPermission)mySocketPermission1.Intersect(mySocketPermissionUnion);

     // mySocketPermissionIntersect should now contain the permissions of mySocketPermission1.
     if (mySocketPermission1.IsSubsetOf(mySocketPermissionIntersect)){
          Console.WriteLine("This is expected");
     }
    // mySocketPermissionIntersect should not contain the permissios of mySocketPermission2.
     if (mySocketPermission2.IsSubsetOf(mySocketPermissionIntersect)){
          Console.WriteLine("This should not print");
     }


// Creates a copy of the intersect SocketPermission.
     SocketPermission mySocketPermissionIntersectCopy =
                               (SocketPermission)mySocketPermissionIntersect.Copy();

     if (mySocketPermissionIntersectCopy.Equals(mySocketPermissionIntersect)){
     Console.WriteLine("Copy successfull");
     }


     // Converts a SocketPermission to XML format and then immediately converts it back to a SocketPermission.
     mySocketPermission1.FromXml(mySocketPermission1.ToXml());

     // Checks to see if permission for this socket resource is unrestricted.  If it is, then there is no need to
     // demand that permissions be enforced.
     if (mySocketPermissionUnion.IsUnrestricted()){
        
          //Do nothing.  There are no restrictions.
     }
     else{
         // Enforces the permissions found in mySocketPermissionUnion on any Socket Resources used below this statement.
         mySocketPermissionUnion.Demand();
     }

    IPHostEntry myIpHostEntry = Dns.Resolve("www.contoso.com");
    IPEndPoint myLocalEndPoint = new IPEndPoint(myIpHostEntry.AddressList[0], 11000);

       Socket s = new Socket(myLocalEndPoint.Address.AddressFamily,
                                   SocketType.Stream,
                                         ProtocolType.Tcp);
       try{
            s.Connect(myLocalEndPoint);
       }
       catch (Exception e){
            Console.WriteLine("Exception Thrown: " + e.ToString());
       }

      // Perform all socket operations in here.

      s.Close();
   ' Creates a SocketPermission restricting access to and from all URIs.
   Dim mySocketPermission1 As New SocketPermission(PermissionState.None)
   
   ' The socket to which this permission will apply will allow connections from www.contoso.com.
   mySocketPermission1.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "www.contoso.com", 11000)
   
   ' Creates a SocketPermission which will allow the target Socket to connect with www.southridgevideo.com.
   Dim mySocketPermission2 As New SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "www.southridgevideo.com", 11002)
   
   ' Creates a SocketPermission from the union of two SocketPermissions.
   Dim mySocketPermissionUnion As SocketPermission = CType(mySocketPermission1.Union(mySocketPermission2), SocketPermission)
   
   ' Checks to see if the union was successfully created by using the IsSubsetOf method.
   If mySocketPermission1.IsSubsetOf(mySocketPermissionUnion) And mySocketPermission2.IsSubsetOf(mySocketPermissionUnion) Then
      Console.WriteLine("This union contains permissions from both mySocketPermission1 and mySocketPermission2")
      
      ' Prints the allowable accept URIs to the console.
      Console.WriteLine("This union accepts connections on :")
      
      Dim myEnumerator As IEnumerator = mySocketPermissionUnion.AcceptList
      While myEnumerator.MoveNext()
         Console.WriteLine(CType(myEnumerator.Current, EndpointPermission).ToString())
      End While
      
      Console.WriteLine("This union establishes connections on : ")
      
      ' Prints the allowable connect URIs to the console.
      Console.WriteLine("This union permits connections to :")
      
      myEnumerator = mySocketPermissionUnion.ConnectList
      While myEnumerator.MoveNext()
         Console.WriteLine(CType(myEnumerator.Current, EndpointPermission).ToString())
      End While
   End If 
   ' Creates a SocketPermission from the intersect of two SocketPermissions.
   Dim mySocketPermissionIntersect As SocketPermission = CType(mySocketPermission1.Intersect(mySocketPermissionUnion), SocketPermission)
   
   ' mySocketPermissionIntersect should now contain the permissions of mySocketPermission1.
   If mySocketPermission1.IsSubsetOf(mySocketPermissionIntersect) Then
      Console.WriteLine("This is expected")
   End If
   ' mySocketPermissionIntersect should not contain the permissios of mySocketPermission2.
   If mySocketPermission2.IsSubsetOf(mySocketPermissionIntersect) Then
      Console.WriteLine("This should not print")
   End If
   
   ' Creates a copy of the intersect SocketPermission.
   Dim mySocketPermissionIntersectCopy As SocketPermission = CType(mySocketPermissionIntersect.Copy(), SocketPermission)
   
   If mySocketPermissionIntersectCopy.Equals(mySocketPermissionIntersect) Then
      Console.WriteLine("Copy successfull")
   End If
   ' Converts a SocketPermission to XML format and then immediately converts it back to a SocketPermission.
   mySocketPermission1.FromXml(mySocketPermission1.ToXml())
   
   
   ' Checks to see if permission for this socket resource is unrestricted.  If it is, then there is no need to
   ' demand that permissions be enforced.
   If mySocketPermissionUnion.IsUnrestricted() Then
   
   'Do nothing.  There are no restrictions.
   Else
      ' Enforces the permissions found in mySocketPermissionUnion on any Socket Resources used below this statement. 
      mySocketPermissionUnion.Demand()
   End If
   
   Dim myIpHostEntry As IPHostEntry = Dns.Resolve("www.contoso.com")
   Dim myLocalEndPoint As New IPEndPoint(myIpHostEntry.AddressList(0), 11000)
   
   Dim s As New Socket(myLocalEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
   Try
      s.Connect(myLocalEndPoint)
   Catch e As Exception
      Console.WriteLine(("Exception Thrown: " + e.ToString()))
   End Try
   
   ' Perform all socket operations in here.
   s.Close()
End Sub

Comentários

SocketPermission as instâncias do controlam a permissão para aceitar conexões ou iniciar Socket conexões.SocketPermission instances control permission to accept connections or initiate Socket connections. Uma Socket permissão pode ser estabelecida para um nome de host ou endereço IP, um número de porta e um protocolo de transporte.A Socket permission can be established for a host name or IP address, a port number, and a transport protocol.

Observação

Evite criar permissões de soquete usando nomes de host, pois esses nomes precisam ser resolvidos para endereços IP, e isso pode bloquear a pilha.Avoid creating socket permissions using host names, as these names have to be resolved to IP addresses, and this might block the stack.

Construtores

SocketPermission(NetworkAccess, TransportType, String, Int32)

Inicializa uma nova instância da classe SocketPermission para o endereço de transporte determinado com a permissão especificada.Initializes a new instance of the SocketPermission class for the given transport address with the specified permission.

SocketPermission(PermissionState)

Inicializa uma nova instância da classe SocketPermission que dá acesso irrestrito ao Socket ou impede o acesso ao Socket.Initializes a new instance of the SocketPermission class that allows unrestricted access to the Socket or disallows access to the Socket.

Campos

AllPorts

Define uma constante que representa todas as portas.Defines a constant that represents all ports.

Propriedades

AcceptList

Obtém uma lista de instâncias EndpointPermission que identifica os pontos de extremidade que podem ser aceitos no âmbito dessa instância de permissão.Gets a list of EndpointPermission instances that identifies the endpoints that can be accepted under this permission instance.

ConnectList

Obtém uma lista de instâncias EndpointPermission que identifica os pontos de extremidade que podem ser conectados no âmbito dessa instância de permissão.Gets a list of EndpointPermission instances that identifies the endpoints that can be connected to under this permission instance.

Métodos

AddPermission(NetworkAccess, TransportType, String, Int32)

Adiciona uma permissão ao conjunto de permissões de um endereço de transporte.Adds a permission to the set of permissions for a transport address.

Assert()

Declara que o código de chamada pode acessar o recurso protegido por uma demanda de permissão através do código que chama este método, mesmo que os chamadores na pilha não tenham recebido permissão para acessar o recurso.Declares that the calling code can access the resource protected by a permission demand through the code that calls this method, even if callers higher in the stack have not been granted permission to access the resource. Usar Assert() pode criar problemas de segurança.Using Assert() can create security issues.

(Herdado de CodeAccessPermission)
Copy()

Cria uma cópia de uma instância SocketPermission.Creates a copy of a SocketPermission instance.

Demand()

Força um SecurityException no tempo de execução se todos os chamadores no topo da pilha de chamadas não receberam as permissões especificadas pela instância atual.Forces a SecurityException at run time if all callers higher in the call stack have not been granted the permission specified by the current instance.

(Herdado de CodeAccessPermission)
Deny()
Obsoleto.
Obsoleto.

Impede que os chamadores no nível superior da pilha de chamadas usem o código que chama esse método para acessar o recurso especificado pela instância atual.Prevents callers higher in the call stack from using the code that calls this method to access the resource specified by the current instance.

(Herdado de CodeAccessPermission)
Equals(Object)

Determina se o objeto CodeAccessPermission especificado é igual ao CodeAccessPermission atual.Determines whether the specified CodeAccessPermission object is equal to the current CodeAccessPermission.

(Herdado de CodeAccessPermission)
FromXml(SecurityElement)

Reconstrói uma instância SocketPermission para uma codificação de XML.Reconstructs a SocketPermission instance for an XML encoding.

GetHashCode()

Obtém um código hash para o objeto CodeAccessPermission atual, adequado para algoritmos de hash e estruturas de dados, tais como uma tabela de hash.Gets a hash code for the CodeAccessPermission object that is suitable for use in hashing algorithms and data structures such as a hash table.

(Herdado de CodeAccessPermission)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
Intersect(IPermission)

Retorna a interseção lógica entre duas instâncias SocketPermission.Returns the logical intersection between two SocketPermission instances.

IsSubsetOf(IPermission)

Determina se a permissão atual é um subconjunto da permissão especificada.Determines if the current permission is a subset of the specified permission.

IsUnrestricted()

Verifica o estado de permissão geral do objeto.Checks the overall permission state of the object.

MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
PermitOnly()

Impede que os chamadores no topo da pilha de chamadas usem o código que chama esse método para acessar todos os recursos, com exceção do recurso especificado pela instância atual.Prevents callers higher in the call stack from using the code that calls this method to access all resources except for the resource specified by the current instance.

(Herdado de CodeAccessPermission)
ToString()

Cria e retorna uma representação de cadeia de caracteres do objeto de permissão atual.Creates and returns a string representation of the current permission object.

(Herdado de CodeAccessPermission)
ToXml()

Cria uma codificação de XML de uma instância SocketPermission e de seu estado atual.Creates an XML encoding of a SocketPermission instance and its current state.

Union(IPermission)

Retorna a união lógica entre duas instâncias SocketPermission.Returns the logical union between two SocketPermission instances.

Implantações explícitas de interface

IPermission.Demand()

Gera um SecurityException em tempo de execução se o requisito de segurança não é atendido.Throws a SecurityException at run time if the security requirement is not met.

(Herdado de CodeAccessPermission)
IStackWalk.Assert()

Declara que código de chamada pode acessar o recurso identificado pelo objeto de permissão atual, mesmo que os chamadores na pilha não tenham recebido permissão para acessar o recurso.Asserts that the calling code can access the resource identified by the current permission object, even if callers higher in the stack have not been granted permission to access the resource.

(Herdado de CodeAccessPermission)
IStackWalk.Demand()

Determina em tempo de execução se a permissão especificada pelo objeto de permissão atual foi ou não concedida a todos os chamadores na pilha de chamadas.Determines at run time whether all callers in the call stack have been granted the permission specified by the current permission object.

(Herdado de CodeAccessPermission)
IStackWalk.Deny()

Faz com que cada Demand() para o objeto atual que passa pelo código de chamada falhe.Causes every Demand() for the current object that passes through the calling code to fail.

(Herdado de CodeAccessPermission)
IStackWalk.PermitOnly()

Causa a falha de cada Demand() de todos os objetos que passam pelo código de chamada, exceto o atual, mesmo que o código superior na pilha de chamadas tenha recebido permissão para acessar outros recursos.Causes every Demand() for all objects except the current one that pass through the calling code to fail, even if code higher in the call stack has been granted permission to access other resources.

(Herdado de CodeAccessPermission)

Aplica-se a