c# UDP Socket

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bobido
    New Member
    • Feb 2008
    • 13

    c# UDP Socket

    Hi there,

    In C# i would like to listen to the following socket:

    Local Address: 0.0.0.0
    Local Port: 1498
    Remote Adress: 127.0.0.1
    Remote Port: 40001
    Protocol: UDP

    I tried with the following code:

    Code:
    try
                {
                    Socket soUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    soUdp.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                    
                    string RemoteIP = "127.0.0.1";
                    IPAddress remoteadres = IPAddress.Parse(RemoteIP);
    
                    IPEndPoint LocalIpEndPoint = new IPEndPoint(remoteadres, 40001);
                    //soUdp.Bind(LocalIpEndPoint);
                    soUdp.Connect(LocalIpEndPoint);
    
                    while (true)
                    {
                        Byte[] recieved = new Byte[1500];
    
                        IPEndPoint tmpIpEndPoint = new IPEndPoint(remoteadres, 40001);
                        EndPoint remoteEP = (tmpIpEndPoint);
                        int BytesRecevied = soUdp.ReceiveFrom(recieved, ref remoteEP);
    
                        string dataRecieved = System.Text.ASCIIEncoding.ASCII.GetString(recieved);
                        Console.WriteLine(dataRecieved.ToString());
                    }
                }
                catch(Exception exc)
                {
                    Console.WriteLine("Socket Exception:\n" + exc.ToString());
                }
    
                Console.WriteLine("Press enter to close window");
                Console.ReadLine();
    I cant recieve anything, although Socket Spy Packet Sniffer does show packet data is being send. Any suggestions on how to achieve this :s.

    Thx in advance!
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    Try this code

    May I suggest a snippet from my own code that I use all the time?
    You'll need to adjust a couple variable names to match your code, but I use names that are easy to read.

    listenPort is set before calling this method, rather than hard code values into it.
    I commented out the line to convert the received data to ASCII since I don't know if that applies to what you are doing.

    Something to note that might help: IPAddress.Any
    This way you aren't listening for messages from a specific address, but from any address. Once you know that works, you can narrow down just one address.

    Code:
                public void StartListener()
                {
                    IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
    				done = false;
                    try
                    {
                        while (!done)
                        {
                            Console.WriteLine("Waiting for broadcast");
    						if (listener != null)
    						{
    							byte[] bytes = listener.Receive(ref groupEP);
    							string FullMsg =  Encoding.Default.GetString(bytes, 0, bytes.Length);
    							Console.WriteLine("Received broadcast from {0} :\n {1}\n",
    								groupEP.ToString(), FullMsg);
    								/*Encoding.ASCII.GetString(bytes, 0, bytes.Length));*/
    							ReceivedMsg(FullMsg);// Raise and event with the message, for any class that subscribes
    						}
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                    finally
                    {
                        if (listener !=null) listener.Close();
    					StartListener();
                    }
                }
    			public void StopListener()
    			{
    				done = true;
    			}

    Comment

    • juing
      New Member
      • Apr 2009
      • 10

      #3
      Hi, just a comment ...

      Connect method is not useful in case of UDP sockets.
      MSDN says this:
      "If you are using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. If you do call Connect, any datagrams that arrive from an address other than the specified default will be discarded. If you want to set your default remote host to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionNam e.Broadcast, or Connect will throw a SocketException . If you receive a SocketException , use the SocketException .ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error."

      Hope it'll help.
      juing

      Comment

      Working...