473,398 Members | 2,165 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

c# UDP Socket

13
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!
May 24 '09 #1
2 19798
tlhintoq
3,525 Expert 2GB
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.  
May 25 '09 #2
juing
10
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
May 25 '09 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: simon place | last post by:
Spent some very frustrating hours recoding to find a way of closing a server socket, i'd not thought it would be any problem, however, after complete failure and as a last resort, i looked at the...
4
by: DreJoh | last post by:
I've read many articles on the subject and the majority of them give the same solution that's in article 821625 on the MSDN website. I'm using the following code and when a the client disconnects...
4
by: Chris Tanger | last post by:
Context: C# System.Net.Sockets Socket created with constructor prarmeters Internetwork, Stream and TCP everything else is left at the default parameters and options except linger may be changed...
0
by: Macca | last post by:
Hi, I am writing an asychronous socket server to handle 20+ simulataneous connections. I have used the example in MSDN as a base. The code is shown at end of question. Each connection has a...
1
by: bobano | last post by:
Hi everyone, I am writing a POP3 Client program in Perl. You connect to a POP3 Server and have a running conversation with the mail server using commands from the RFC 1939 Post Office Protocol....
3
by: BuddyWork | last post by:
Hello, Could someone please explain why the Socket.Send is slow to send to the same process it sending from. Eg. Process1 calls Socket.Send which sends to the same IP address and port, the...
0
by: Buddy Home | last post by:
There is two examples of code. Example 1. Send and Receive within the same process. Put this code in a console app called SendAndReceive and run the code. using System; using...
5
by: darthghandi | last post by:
I've created a class to listen to all interfaces and do a BeginAccept(). Once it gets a connection, it passes the connected socket off and stores it in a List. Next, it continues to listen for...
2
by: kashifjawed | last post by:
I'm developing a c# asynchronous socket application for tranfering file or large data from client to server and server to client as well in chunks. Application sometimes transfer file from client...
1
Airslash
by: Airslash | last post by:
Hello, The problem is that my server is not receiving data. The code below are the various classes I designed around sockets. It will be big... I have run the code with the debugger, and I see...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.