Exporter (0) Imprimer
Développer tout
Cet article a fait l'objet d'une traduction automatique. Déplacez votre pointeur sur les phrases de l'article pour voir la version originale de ce texte. Informations supplémentaires.
Traduction
Source

MulticastOption, classe

Contient les valeurs IPAddress utilisées pour joindre et déplacer des groupes multicast.

System.Object
  System.Net.Sockets.MulticastOption

Espace de noms :  System.Net.Sockets
Assembly :  System (dans System.dll)

public class MulticastOption

Le type MulticastOption expose les membres suivants.

  NomDescription
Méthode publiqueMulticastOption(IPAddress)Initialise une nouvelle version de la classe MulticastOption pour le groupe multicast IP spécifié.
Méthode publiqueMulticastOption(IPAddress, Int32)Initialise une nouvelle instance de la classe MulticastOption avec l'adresse de groupe multicast IP et l'index d'interface spécifiés.
Méthode publiqueMulticastOption(IPAddress, IPAddress)Initialise une nouvelle instance de la classe MulticastOption avec l'adresse de groupe multicast IP spécifiée et l'adresse IP locale associée à une interface réseau.
Début

  NomDescription
Propriété publiqueGroupObtient ou définit l'adresse IP d'un groupe multicast.
Propriété publiqueInterfaceIndexObtient ou définit l'index d'interface permettant d'envoyer et de recevoir des paquets multicast.
Propriété publiqueLocalAddressObtient ou définit l'adresse locale associée à un groupe multicast.
Début

  NomDescription
Méthode publiqueEquals(Object)Détermine si l'objet spécifié est identique à l'objet actuel. (Hérité de Object.)
Méthode protégéeFinalize Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de nettoyage avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.)
Méthode publiqueGetHashCodeSert de fonction de hachage par défaut. (Hérité de Object.)
Méthode publiqueGetTypeObtient le Type de l'instance actuelle. (Hérité de Object.)
Méthode protégéeMemberwiseCloneCrée une copie superficielle de l'objet Object actuel. (Hérité de Object.)
Méthode publiqueToStringRetourne une chaîne qui représente l'objet actif. (Hérité de Object.)
Début

Utilisez MulticastOption pour stocker le IPAddress d'un groupe multicast que vous voulez joindre ou déplacer. Utilisez la méthode Socket.SetSocketOption avec les paramètres suivants pour joindre un groupe multicast.

Paramètre

Valeur

socketOptionLevel

SocketOptionLevel.Udp

socketOptionName

AddMembership

object

MulticastOption

Utilisez le champ DropMembership pour déplacer un groupe multicast.

Les exemples suivants associent l'interface IP par défaut à un groupe multicast IP. Ils supposent que l'adresse de groupe multicast IP est comprise entre 224.0.0.0 et 239.255.255.255.


' This is the listener example that shows how to use the MulticastOption class. 
' In particular, it shows how to use the MulticastOption(IPAddress, IPAddress) 
' constructor, which you need to use if you have a host with more than one 
' network card.
' The first parameter specifies the multicast group address, and the second 
' specifies the local address of the network card you want to use for the data
' exchange.
' You must run this program in conjunction with the sender program as 
' follows:
' Open a console window and run the listener from the command line. 
' In another console window run the sender. In both cases you must specify 
' the local IPAddress to use. To obtain this address run the ipconfig comand 
' from the command line. 


Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports Microsoft.VisualBasic


Namespace Mssc.TransportProtocols.Utilities

  Module M_TestMulticastOption

    Public Class TestMulticastOption

      Private Shared mcastAddress As IPAddress
      Private Shared mcastPort As Integer
      Private Shared mcastSocket As Socket
      Private Shared mcastOption As MulticastOption


      Private Shared Sub MulticastOptionProperties()
        Console.WriteLine(("Current multicast group is: " + mcastOption.Group.ToString()))
        Console.WriteLine(("Current multicast local address is: " + mcastOption.LocalAddress.ToString()))
      End Sub 'MulticastOptionProperties


      Private Shared Sub StartMulticast()

        Try
          mcastSocket = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)

          Console.Write("Enter the local IP address: ")

          Dim localIPAddr As IPAddress = IPAddress.Parse(Console.ReadLine())

          'IPAddress localIP = IPAddress.Any;
          Dim localEP As EndPoint = CType(New IPEndPoint(localIPAddr, mcastPort), EndPoint)

          mcastSocket.Bind(localEP)

          ' Define a MulticastOption object specifying the multicast group 
          ' address and the local IPAddress.
          ' The multicast group address is the same as the address used by the server.
          mcastOption = New MulticastOption(mcastAddress, localIPAddr)

          mcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption)

        Catch e As Exception
          Console.WriteLine(e.ToString())
        End Try
      End Sub 'StartMulticast


      Private Shared Sub ReceiveBroadcastMessages()
        Dim done As Boolean = False
        Dim bytes() As Byte = New [Byte](99) {}
        Dim groupEP As New IPEndPoint(mcastAddress, mcastPort)
        Dim remoteEP As EndPoint = CType(New IPEndPoint(IPAddress.Any, 0), EndPoint)


        Try
          While Not done
            Console.WriteLine("Waiting for multicast packets.......")
            Console.WriteLine("Enter ^C to terminate.")

            mcastSocket.ReceiveFrom(bytes, remoteEP)

            Console.WriteLine("Received broadcast from {0} :" + ControlChars.Lf + " {1}" + ControlChars.Lf, groupEP.ToString(), Encoding.ASCII.GetString(bytes, 0, bytes.Length))
          End While



          mcastSocket.Close()

        Catch e As Exception
          Console.WriteLine(e.ToString())
        End Try
      End Sub 'ReceiveBrodcastMessages


      Public Shared Sub Main(ByVal args() As String)
        ' Initialize the multicast address group and multicast port.
        ' Both address and port are selected from the allowed sets as
        ' defined in the related RFC documents. These are the same
        ' as the values used by the sender.
        mcastAddress = IPAddress.Parse("224.168.100.2")
        mcastPort = 11000

        ' Start a multicast group.
        StartMulticast()

        ' Display MulticastOption properties.
        MulticastOptionProperties()

        ' Receive broadcast messages.
        ReceiveBroadcastMessages()
      End Sub 'Main
    End Class 'TestMulticastOption

  End Module

End Namespace




using System;
using System.Net;
using System.Net.Sockets;
using System.Text;


// This is the listener example that shows how to use the MulticastOption class. 
// In particular, it shows how to use the MulticastOption(IPAddress, IPAddress) 
// constructor, which you need to use if you have a host with more than one 
// network card.
// The first parameter specifies the multicast group address, and the second 
// specifies the local address of the network card you want to use for the data
// exchange.
// You must run this program in conjunction with the sender program as 
// follows:
// Open a console window and run the listener from the command line. 
// In another console window run the sender. In both cases you must specify 
// the local IPAddress to use. To obtain this address run the ipconfig comand 
// from the command line. 
//  
namespace Mssc.TransportProtocols.Utilities
{

  public class TestMulticastOption 
  {

    private static IPAddress mcastAddress;
    private static int mcastPort;
    private static Socket mcastSocket;
    private static MulticastOption mcastOption;


    private static void MulticastOptionProperties()
    {
      Console.WriteLine("Current multicast group is: " + mcastOption.Group);
      Console.WriteLine("Current multicast local address is: " + mcastOption.LocalAddress);
    }


    private static void StartMulticast() 
    {
	
      try 
      {
        mcastSocket = new Socket(AddressFamily.InterNetwork,
                                 SocketType.Dgram, 
                                 ProtocolType.Udp);
		
        Console.Write("Enter the local IP address: ");

        IPAddress localIPAddr = IPAddress.Parse(Console.ReadLine());

        //IPAddress localIP = IPAddress.Any;
        EndPoint localEP = (EndPoint)new IPEndPoint(localIPAddr, mcastPort);

        mcastSocket.Bind(localEP);


        // Define a MulticastOption object specifying the multicast group 
        // address and the local IPAddress.
        // The multicast group address is the same as the address used by the server.
        mcastOption = new MulticastOption(mcastAddress, localIPAddr);

        mcastSocket.SetSocketOption(SocketOptionLevel.IP, 
                                    SocketOptionName.AddMembership, 
                                    mcastOption);

      } 

      catch (Exception e) 
      {
        Console.WriteLine(e.ToString());
      }
    }

    private static void ReceiveBroadcastMessages() 
    {
      bool done = false;
      byte[] bytes = new Byte[100];
      IPEndPoint groupEP = new IPEndPoint(mcastAddress, mcastPort);
      EndPoint remoteEP = (EndPoint) new IPEndPoint(IPAddress.Any,0);
		

      try 
      {      
        while (!done) 
        {
          Console.WriteLine("Waiting for multicast packets.......");
          Console.WriteLine("Enter ^C to terminate.");

          mcastSocket.ReceiveFrom(bytes, ref remoteEP);

          Console.WriteLine("Received broadcast from {0} :\n {1}\n",
            groupEP.ToString(),
            Encoding.ASCII.GetString(bytes,0,bytes.Length));


        }

        mcastSocket.Close();
      } 

      catch (Exception e) 
      {
        Console.WriteLine(e.ToString());
      }
    }

    public static void Main(String[] args) 
    {
      // Initialize the multicast address group and multicast port.
      // Both address and port are selected from the allowed sets as
      // defined in the related RFC documents. These are the same 
      // as the values used by the sender.
      mcastAddress = IPAddress.Parse("224.168.100.2");
      mcastPort = 11000;

      // Start a multicast group.
      StartMulticast();

      // Display MulticastOption properties.
      MulticastOptionProperties();

      // Receive broadcast messages.
      ReceiveBroadcastMessages();
    }
  }
}



#using <System.dll>

using namespace System;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Text;

// This program shows how to use the MultiCastOption type. In particular,
// it shows how to use the MultiCastOption(IPAddress, IPAddress) constructor,
// You need to use this constructor, in the case of multihomed host (i.e.,
// a host with more than one network card). With the first parameter you
// specify the multicast group address, with the second you specify the
// local address of one of the network cards you want to use for the data
// exchange.
// You must run this program in conjunction with the sender program as
// follows:
// Open a console window and run the listener from the command line.
// In another console window run the sender. In both cases you must specify
// the local IPAddress to use. To obtain this address run the ipconfig from
// the command line.
//
public ref class TestMulticastOption
{
private:
   static IPAddress^ mcastAddress;
   static int mcastPort;
   static Socket^ mcastSocket;
   static MulticastOption^ mcastOption;

   static void MulticastOptionProperties()
   {
      Console::WriteLine( "Current multicast group is: {0}", mcastOption->Group );
      Console::WriteLine( "Current multicast local address is: {0}", mcastOption->LocalAddress );
   }


   static void StartMulticast()
   {
      try
      {
         mcastSocket = gcnew Socket( AddressFamily::InterNetwork,SocketType::Dgram,ProtocolType::Udp );
         Console::Write( "Enter the local IP Address: " );
         IPAddress^ localIPAddr = IPAddress::Parse( Console::ReadLine() );

         //IPAddress localIP = IPAddress::Any;
         EndPoint^ localEP = dynamic_cast<EndPoint^>(gcnew IPEndPoint( localIPAddr,mcastPort ));
         mcastSocket->Bind( localEP );

         // Define a MuticastOption object specifying the multicast group
         // address and the local IPAddress.
         // The multicast group address is the same one used by the server.
         mcastOption = gcnew MulticastOption( mcastAddress,localIPAddr );
         mcastSocket->SetSocketOption( SocketOptionLevel::IP, SocketOptionName::AddMembership, mcastOption );

      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e );
      }

   }

   static void ReceiveBrodcastMessages()
   {
      bool done = false;
      array<Byte>^bytes = gcnew array<Byte>(100);
      IPEndPoint^ groupEP = gcnew IPEndPoint( mcastAddress,mcastPort );
      EndPoint^ remoteEP = dynamic_cast<EndPoint^>(gcnew IPEndPoint( IPAddress::Any,0 ));
      try
      {
         while (  !done )
         {
            Console::WriteLine( "Waiting for Multicast packets......." );
            Console::WriteLine( "Enter ^C to terminate." );
            mcastSocket->ReceiveFrom( bytes, remoteEP );
            Console::WriteLine( "Received broadcast from {0} :\n {1}\n", groupEP, Encoding::ASCII->GetString( bytes, 0, bytes->Length ) );
         }
         mcastSocket->Close();
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e );
      }

   }


public:
   static void Main()
   {

      // Initialize multicast address group and multicast port.
      // Both address and port are selected from the allowed sets as
      // defined in the related RFC documents. These are the same values
      // used by the sender.
      mcastAddress = IPAddress::Parse( "224.168.100.2" );
      mcastPort = 11000;

      // Start a multicast group.
      StartMulticast();

      // Display multicast option properties.
      MulticastOptionProperties();

      // Receive brodcast messages.
      ReceiveBrodcastMessages();
   }

};

int main()
{
   TestMulticastOption::Main();
}




' This sender example must be used in conjunction with the listener program.
' You must run this program as follows:
' Open a console window and run the listener from the command line. 
' In another console window run the sender. In both cases you must specify 
' the local IPAddress to use. To obtain this address, run the ipconfig command
' from the command line. 
'  
Imports System
Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Imports Microsoft.VisualBasic

Namespace Mssc.TransportProtocols.Utilities

  Module M_TestMulticastOption

    Class TestMulticastOption

      Private Shared mcastAddress As IPAddress
      Private Shared mcastPort As Integer
      Private Shared mcastSocket As Socket


      Shared Sub JoinMulticastGroup()
        Try
          ' Create a multicast socket.
          mcastSocket = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)

          ' Get the local IP address used by the listener and the sender to
          ' exchange multicast messages. 
          Console.Write(ControlChars.Lf + "Enter local IPAddress for sending multicast packets: ")
          Dim localIPAddr As IPAddress = IPAddress.Parse(Console.ReadLine())

          ' Create an IPEndPoint object. 
          Dim IPlocal As New IPEndPoint(localIPAddr, 0)

          ' Bind this endpoint to the multicast socket.
          mcastSocket.Bind(IPlocal)

          ' Define a MulticastOption object specifying the multicast group 
          ' address and the local IP address.
          ' The multicast group address is the same as the address used by the listener.
          Dim mcastOption As MulticastOption
          mcastOption = New MulticastOption(mcastAddress, localIPAddr)

          mcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption)

        Catch e As Exception
          Console.WriteLine((ControlChars.Lf + e.ToString()))
        End Try
      End Sub 'JoinMulticast


      Shared Sub BroadcastMessage(ByVal message As String)
        Dim endPoint As IPEndPoint

        Try
          'Send multicast packets to the listener.
          endPoint = New IPEndPoint(mcastAddress, mcastPort)
          mcastSocket.SendTo(ASCIIEncoding.ASCII.GetBytes(message), endPoint)
          Console.WriteLine("Multicast data sent.....")
        Catch e As Exception
          Console.WriteLine((ControlChars.Lf + e.ToString()))
        End Try

        mcastSocket.Close()
      End Sub 'BrodcastMessage


      Public Shared Sub Main(ByVal args() As String)
        ' Initialize the multicast address group and multicast port.
        ' Both address and port are selected from the allowed sets as
        ' defined in the related RFC documents. These are the same as the 
        ' values used by the sender.
        mcastAddress = IPAddress.Parse("224.168.100.2")
        mcastPort = 11000

        ' Join the listener multicast group.
        JoinMulticastGroup()

        ' Broadcast the message to the listener.
        BroadcastMessage("Hello multicast listener.")
      End Sub 'Main
    End Class 'TestMulticastOption

  End Module

End Namespace




using System;
using System.Net.Sockets;
using System.Net;
using System.Text;

// This sender example must be used in conjunction with the listener program.
// You must run this program as follows:
// Open a console window and run the listener from the command line. 
// In another console window run the sender. In both cases you must specify 
// the local IPAddress to use. To obtain this address,  run the ipconfig command 
// from the command line. 
//  
namespace Mssc.TransportProtocols.Utilities
{
  class TestMulticastOption
  {

    static IPAddress mcastAddress;
    static int mcastPort;
    static Socket mcastSocket;

    static void JoinMulticastGroup()
    {
      try
      {
        // Create a multicast socket.
        mcastSocket = new Socket(AddressFamily.InterNetwork, 
                                 SocketType.Dgram, 
                                 ProtocolType.Udp);
			  
        // Get the local IP address used by the listener and the sender to
        // exchange multicast messages. 
        Console.Write("\nEnter local IPAddress for sending multicast packets: ");
        IPAddress  localIPAddr = IPAddress.Parse(Console.ReadLine());

        // Create an IPEndPoint object. 
        IPEndPoint IPlocal = new IPEndPoint(localIPAddr, 0);

        // Bind this endpoint to the multicast socket.
        mcastSocket.Bind(IPlocal);

        // Define a MulticastOption object specifying the multicast group 
        // address and the local IP address.
        // The multicast group address is the same as the address used by the listener.
        MulticastOption mcastOption;
        mcastOption = new MulticastOption(mcastAddress, localIPAddr);

        mcastSocket.SetSocketOption(SocketOptionLevel.IP, 
                                    SocketOptionName.AddMembership, 
                                    mcastOption);

      }
      catch (Exception e)
      {
        Console.WriteLine("\n" + e.ToString());
      }
    }

    static void BroadcastMessage(string message)
    {
      IPEndPoint endPoint;

      try
      {
        //Send multicast packets to the listener.
        endPoint = new IPEndPoint(mcastAddress,mcastPort);
        mcastSocket.SendTo(ASCIIEncoding.ASCII.GetBytes(message), endPoint);			
        Console.WriteLine("Multicast data sent.....");
      }
      catch (Exception e)
      {
        Console.WriteLine("\n" + e.ToString());
      }

      mcastSocket.Close();
    }


    static void Main(string[] args)
    {
      // Initialize the multicast address group and multicast port.
      // Both address and port are selected from the allowed sets as
      // defined in the related RFC documents. These are the same 
      // as the values used by the sender.
      mcastAddress = IPAddress.Parse("224.168.100.2");
      mcastPort = 11000;

      // Join the listener multicast group.
      JoinMulticastGroup();

      // Broadcast the message to the listener.
      BroadcastMessage("Hello multicast listener.");
    }
  }
}



#using <System.dll>

using namespace System;
using namespace System::Net::Sockets;
using namespace System::Net;
using namespace System::Text;

// This is an auxiliary program to be used in conjunction with a listener
// program.
// You must run this program as follows:
// Open a console window and run the listener from the command line.
// In another console window run the sender. In both cases you must specify
// the local IPAddress to use. To obtain this address run the ipconfig
// from the command line.
//
ref class TestMulticastOption
{
private:
   static IPAddress^ mcastAddress;
   static int mcastPort;
   static Socket^ mcastSocket;
   static void JoinMulticast()
   {
      try
      {

         // Create multicast socket.
         mcastSocket = gcnew Socket( AddressFamily::InterNetwork,SocketType::Dgram,ProtocolType::Udp );

         // Get the local IP address used by the listener and the sender to
         // exchange data in a multicast fashion.
         Console::Write( "\nEnter local IPAddress for sending multicast packets: " );
         IPAddress^ localIPAddr = IPAddress::Parse( Console::ReadLine() );

         // Create an IPEndPoint Object*.
         IPEndPoint^ IPlocal = gcnew IPEndPoint( localIPAddr,0 );

         // Bind this end point to the multicast socket.
         mcastSocket->Bind( IPlocal );

         // Define a MuticastOption Object* specifying the multicast group
         // address and the local IPAddress.
         // The multicast group address is the same one used by the listener.
         MulticastOption^ mcastOption;
         mcastOption = gcnew MulticastOption( mcastAddress,localIPAddr );
         mcastSocket->SetSocketOption( SocketOptionLevel::IP, SocketOptionName::AddMembership, mcastOption );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( "\n {0}", e );
      }

   }

   static void BrodcastMessage( String^ message )
   {
      IPEndPoint^ endPoint;
      try
      {

         //Send multicast packets to the listener.
         endPoint = gcnew IPEndPoint( mcastAddress,mcastPort );
         mcastSocket->SendTo( ASCIIEncoding::ASCII->GetBytes( message ), endPoint );
         Console::WriteLine( "Multicast data sent....." );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( "\n {0}", e );
      }

      mcastSocket->Close();
   }


public:
   static void main()
   {

      // Initialize multicast address group and multicast port.
      // Both address and port are selected from the allowed sets as
      // defined in the related RFC documents. These are the same values
      // used by the sender.
      mcastAddress = IPAddress::Parse( "224.168.100.2" );
      mcastPort = 11000;

      // Join the listener multicast group.
      JoinMulticast();

      // Broadcast message to the listener.
      BrodcastMessage( "Hello multicast listener." );
   }

};

int main()
{
   TestMulticastOption::main();
}



.NET Framework

Pris en charge dans : 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Pris en charge dans : 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (rôle principal du serveur non pris en charge), Windows Server 2008 R2 (rôle principal du serveur pris en charge avec SP1 ou version ultérieure ; Itanium non pris en charge)

Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.

Tous les membres static (Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

Ajouts de la communauté

AJOUTER
Afficher:
© 2014 Microsoft