Connecting Tech Pros Worldwide Forums | Help | Site Map

c# UDP Socket

Newbie
 
Join Date: Feb 2008
Posts: 13
#1: May 24 '09
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:

Expand|Select|Wrap|Line Numbers
  1. try
  2.             {
  3.                 Socket soUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  4.                 soUdp.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
  5.  
  6.                 string RemoteIP = "127.0.0.1";
  7.                 IPAddress remoteadres = IPAddress.Parse(RemoteIP);
  8.  
  9.                 IPEndPoint LocalIpEndPoint = new IPEndPoint(remoteadres, 40001);
  10.                 //soUdp.Bind(LocalIpEndPoint);
  11.                 soUdp.Connect(LocalIpEndPoint);
  12.  
  13.                 while (true)
  14.                 {
  15.                     Byte[] recieved = new Byte[1500];
  16.  
  17.                     IPEndPoint tmpIpEndPoint = new IPEndPoint(remoteadres, 40001);
  18.                     EndPoint remoteEP = (tmpIpEndPoint);
  19.                     int BytesRecevied = soUdp.ReceiveFrom(recieved, ref remoteEP);
  20.  
  21.                     string dataRecieved = System.Text.ASCIIEncoding.ASCII.GetString(recieved);
  22.                     Console.WriteLine(dataRecieved.ToString());
  23.                 }
  24.             }
  25.             catch(Exception exc)
  26.             {
  27.                 Console.WriteLine("Socket Exception:\n" + exc.ToString());
  28.             }
  29.  
  30.             Console.WriteLine("Press enter to close window");
  31.             Console.ReadLine();
  32.  
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's Avatar
Moderator
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 2,305
#2: May 25 '09

re: c# UDP Socket


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.

Expand|Select|Wrap|Line Numbers
  1.             public void StartListener()
  2.             {
  3.                 IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
  4.                 done = false;
  5.                 try
  6.                 {
  7.                     while (!done)
  8.                     {
  9.                         Console.WriteLine("Waiting for broadcast");
  10.                         if (listener != null)
  11.                         {
  12.                             byte[] bytes = listener.Receive(ref groupEP);
  13.                             string FullMsg =  Encoding.Default.GetString(bytes, 0, bytes.Length);
  14.                             Console.WriteLine("Received broadcast from {0} :\n {1}\n",
  15.                                 groupEP.ToString(), FullMsg);
  16.                                 /*Encoding.ASCII.GetString(bytes, 0, bytes.Length));*/
  17.                             ReceivedMsg(FullMsg);// Raise and event with the message, for any class that subscribes
  18.                         }
  19.                     }
  20.                 }
  21.                 catch (Exception e)
  22.                 {
  23.                     Console.WriteLine(e.ToString());
  24.                 }
  25.                 finally
  26.                 {
  27.                     if (listener !=null) listener.Close();
  28.                     StartListener();
  29.                 }
  30.             }
  31.             public void StopListener()
  32.             {
  33.                 done = true;
  34.             }
  35.  
  36.  
Newbie
 
Join Date: Apr 2009
Posts: 10
#3: May 25 '09

re: c# UDP Socket


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 SocketOptionName.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
Reply