Find Broadcast address for sending UDP message

Asked

Viewed 387 times

2

My Wi-Fi network interface contains the following settings:

Wireless LAN adapter Wi-Fi:

Connection-specific DNS Suffix  . : home
Link-local IPv6 Address . . . . . : fe80::95d7:bda0:eac3:ebf7%5
IPv4 Address. . . . . . . . . . . : 192.168.1.2
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.1.1

One way for me to send a text stream is by using the UDP protocol.

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

class Program
{
    static void Main(string[] args)
    {
    Socket emissor = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    IPAddress destinatario = IPAddress.Parse("192.168.1.255");
    IPEndPoint emissor_end_point = new IPEndPoint(destinatario, 33333);

    Console.WriteLine("Digite a mensagem a enviar:");
    string mensagem = Console.ReadLine();
    byte[] mensagem_buffer = Encoding.ASCII.GetBytes(mensagem);

    emissor.SendTo(mensagem_buffer, emissor_end_point);
    emissor.Close();

    Console.WriteLine("Mensagem enviada ...");
    Console.ReadKey();
    }
}

In the case of an IP address of class C, in order to send the broadcast just change the last Octeto to 255.

It is possible to get this ip address automatically regardless of the network where the program runs?

I wanted to avoid the "fastidious" process of processing text with the strings associated with ip and its mask.

  • I did not understand very well what you want, it would be to get the IP address of a computer network automatically?

  • Voce wants to send a broadcast message so that all hosts connected to the network receive and this?

  • Yes ... but I don’t want to have to write the ip address of the network where I am in the code.

  • if Voce is wanting to get the network mask automatically I do not know if with socket is possible but with threads of the system probably yes

  • I am also forgetting that a host may have more than one interface ... which further complicates the scenario.

2 answers

3

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

class Program
{
    static void Main(string[] args)
    {
    Socket emissor = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    // IPAddress destinatario = IPAddress.Parse("192.168.1.255");
    udpSocket.EnableBroadcast = true;
    IPAddress destinatario = IPAddress.Broadcast
    IPEndPoint emissor_end_point = new IPEndPoint(destinatario, 33333);

    Console.WriteLine("Digite a mensagem a enviar:");
    string mensagem = Console.ReadLine();
    byte[] mensagem_buffer = Encoding.ASCII.GetBytes(mensagem);

    emissor.SendTo(mensagem_buffer, emissor_end_point);
    emissor.Close();

    Console.WriteLine("Mensagem enviada ...");
    Console.ReadKey();
    }
}

Restraint Socket.Enablebroadcast Property, Camp Ipaddress.Broadcast

Another example of very poorly written code taken from the site MSDN to receive datagrams UDP

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

public class UDPListener 
{
    private const int listenPort = 11000;

    private static void StartListener() 
    {
        bool done = false;

        UdpClient listener = new UdpClient(listenPort);
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any,listenPort);

        try 
        {
            while (!done) 
            {
                Console.WriteLine("Waiting for broadcast");
                byte[] bytes = listener.Receive( ref groupEP);

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

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

    public static int Main() 
    {
        StartListener();

        return 0;
    }
}

1

I leave my final version of the elementary emitter/receiver.

Emitter

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

class Program
{
    static void Main(string[] args)
    {
        //Declarações
        int porto = 33333;
        Socket emissor = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPAddress destinatario = IPAddress.Broadcast;
        emissor.EnableBroadcast = true;
        IPEndPoint emissorEndPoint = new IPEndPoint(destinatario, porto);

        // Enviar mensagem
        Console.WriteLine("Digite a mensagem a enviar:");
        string mensagem = Console.ReadLine();
        byte[] mensagemBuffer = Encoding.ASCII.GetBytes(mensagem);
        emissor.SendTo(mensagemBuffer, emissorEndPoint);
        emissor.Close();

        //Terminar ...
        Console.WriteLine("Mensagem enviada\nPrima uma tecla para continuar ...");
        Console.ReadKey();
    }
}

Receiver

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

public class Program
{
    public static int Main()
    {
        //Declarações
        int porto = 33333;
        UdpClient recetor = new UdpClient(porto);
        IPEndPoint escutaEndPoint = new IPEndPoint(IPAddress.Any, porto);
        string mensagem;
        byte[] recebidoByteArray;

        //Receção
        Console.WriteLine("A aguardar chegada de mensagem em broadcast...");
        recebidoByteArray = recetor.Receive(ref escutaEndPoint);
        mensagem = Encoding.ASCII.GetString(recebidoByteArray, 0, recebidoByteArray.Length);
        Console.WriteLine("[Mensagem recebida a {0} ] {1}", DateTime.Now, mensagem);
        recetor.Close();

        // Terminar ...
        while (Console.KeyAvailable) Console.ReadKey(false);
        Console.WriteLine("Prima uma tecla para continuar ...");
        Console.ReadKey();
        return 0;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.