Code Snippets
Code Samples

The Blog
Our Projects

::Add RageStorm to Favorites!::

The Blog | Our Projects | Guest Book | About | Contact

Tutorial - UDP
Category:Internet & Networks
Uploaded at:28-May-03
UDP is a simple protocol of transferring data over the internet. It stands for User Datagram Protocol. Unlike TCP, it is not a reliable protocol, you can't know if, when and in which order your data will arrive. However, UDP is much faster than TCP and therefore useful when speed matters like in online games. Note: You should not use UDP for sending files or any other important data as a result of the reasons above, for this stuff use TCP, unless you write your own reliability layer. UDP is a connectionless protocol, that means you don't have to connect to the server before you send your packets.
I'll show you how to set a small server/client... You'd better download the source codes in order to understand it better!
Ok let's start coding!! :)
#define APP_PORT 0x1983 // We define a port that we are going to use.

// Here is a structure contains the port we'll use,
// the protocol type and the IP address we'll communicate with.
SOCKADDR_IN sockaddr;

// This is our socket, it is the handle to the IO address to read/write packets
SOCKET sock;


// First we see if there is a winsock ver 2.2 installed on the computer,
we initizalize the sockets DLL for out app.
if (WSAStartup(MAKEWORD(2, 2), &data) != 0) return(0);

// Here we create our socket, which will be a UDP socket (SOCK_DGRAM).
if (!sock)
 // Creation failed!
//Now we'll set the sockaddr variables:
sockaddr.sin_family = AF_INET; // Must be AF_INET
// If this is the Server:
 sockaddr.sin_addr.s_addr = INADDR_ANY; // Means we will "answer" to all addresses.
// Or if this is the client, set IP of the server to connect to.
 sockaddr.sin_addr.s_addr = inet_addr(""); // IP to communicate with.

// The following sets our communication port.
// 'htons()' reverses the bytes (0x1020 would become 0x2010).
// This metod is called Big Endian and it was first used on Unix systems, you
// have to call it because all systems work that way
sockaddr.sin_port = htons(APP_PORT);

// A server need to bind the socket to itself in order to receive all the packets
// it gets from a port

int ret = bind(sock, (SOCKADDR *)&sockaddr, sizeof(SOCKADDR));
if (ret)
 // Bind failed!

// That's it, now let's send a message...
char buffer[256];
strcpy(buffer, "HELLO!!!");
int len = sizeof(SOCKADDR);
sendto(sock, buffer, strlen(buffer), 0, (SOCKADDR *)&sockaddr, sizeof(SOCKADDR));
// Notice we use sendto() and NOT send(), because we use UDP!

// Easy huh?? Let's receive a packet..

char inbuffer[256];
int len = sizeof(SOCKADDR);
memset(inbuffer, '\0', 256);
recvfrom(sock, inbuffer, sizeof(inbuffer)-1, 0, &from, &len);
MessageBox(NULL, inbuffer, "Incoming Data", MB_OK);
// In the from structure we can see who sent the packet...


OK, that's it for setting up a sever/client and send/receive packets... Now after you know to received and sent packets, let's go on, Have you ever heard of blocking sockets?? Well, think you call recvfrom() and there is no packet to receive, so the system will wait until it receives a packet and JUST then it will get back to your app...This is called the blocking sockets. Now, there are non-blocking sockets. You'll find yourself waiting in a loop 'till you receive the proper return value from a non-blocking socket. So it's a big headache and usually not helpful much. Now let's move to another kind of blocking sockets, but with something better, which is called Select(). You tell your system to tell you when a socket arrives and then you receive a message that tells your app that you can receive the packet, get it? Then if the system tells you that a message arrived you'll just pick it up and you won't have to block your application because there must be a packet to receive! And this makes the Select function so good that you don't need to wait, Windows will message you.
Let's see how to use the WSAAsyncSelect()
// We define a message which will be used by the system to tell that a network
// event occured (in this tutorials - only receiving messages)
#define WM_SOCKETREAD (WM_APP + 100)

// Call WSAAsyncSelect() after you are done setting the server/client variables...
WSAAsyncSelect(sock, g_hWnd, WM_SOCKETREAD, FD_READ);
// This function parameters are the sock we use (to receive the packets from).
// The window that will receive the messages that tell a network event
// occured (packet arrived in our case). // It will send the message to the passed window. // Let's say we created a normal window... // So it must has a WindowProcedure(which will get the message). LRESULT CALLBACK WindProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_SOCKETREAD: { // Here we receive the packet like we did before. SOCKADDR from; char inbuffer[256]; int len = sizeof(SOCKADDR); memset(inbuffer, '\0', 256); recvfrom(sock, inbuffer, sizeof(inbuffer)-1, 0, &from, &len); }break; case .... break; case .... break; } return(DefWindowProc(hWnd, msg, wParam, lParam)); }

Kewl function huh?? You'll be using it a lot if you set a timer and see if there is a message in the queue waiting for us to read it! I'm going to take some nap I hope you understand all this UDP stuff and espcially the WSAAsyncSelect() because you'll use it in TCP too :) Farewell
BTW-Download the source code you'll see how all the code works TOGETHER!

Source Code:
Visual C++ 6 - SUDP.zip
Visual C++ 6 - CUDP.zip

User Contributed Comments(48)
 [1] Aaron J. | 2006-02-09 17:46:50

Good tutorial!!
 [2] Praveen Sharna | 2006-04-04 06:11:50

Your Totorial Helped me alot,
Thanks with Regards.
 [3] AY | 2006-08-08 10:07:46

This tutorial is awesome :D It makes networking so simple :D Thanks a bunch for posting this!!
 [4] Kris | 2006-08-31 19:44:49

Useful! But with these two lines:

sockaddr.sin_addr.s_addr = INADDR_ANY; // Means we will "answer" to all addresses.
sockaddr.sin_addr.s_addr = inet_addr(""); // IP to communicate with.

arent you just setting the same variable twice?
 [5] arkon | 2006-09-03 17:51:14

you are right, it's for the sake of example :)
 [6] Chris Done | 2006-10-21 11:37:23

 [7] Michal Gorski | 2006-11-02 11:05:56

Thanks for a v. good tutorial!!

Regards, M. Gorski
 [8] May | 2007-01-19 09:09:17

I like it........thanks alot!
 [9] in2minds | 2007-02-09 16:54:08


loved your code, but i have a small problem.
Here is the explanation:
I modified your server code(Listen) to send out an inquiry packet to my ip camera's.
now when i get response from 2 of my camera, only the last response is displayed in the text box. i know i need to have a do while loop. but how do i append the response to the text box?
another thing is my do while loop dosent become false so the application goes in a hang.


here is that part of code:
        case WM_SOCKETREAD:
            SOCKADDR from;
            char buffer[256];
            int len = sizeof(SOCKADDR);
            memset(buffer, '\0', 256);
            recvfrom(sock, buffer, sizeof(buffer)-1, 0, &from, &len);
    -->>do {
-->>> need to append text here    SetDlgItemText(hDlg, IDC_MESSAGE, buffer);

        }while (buffer > 0)        
 [10] Arun Gite | 2007-07-25 03:28:11

Hi friends,
  This UDP tutorial is really good for those are new to UDP Socket Programming.
  Thanking you
Arun Gite
 [11] Wei Min | 2007-12-21 03:32:02

Hi. Your code was really useful. However, how do i send char values if it's above 127?
i can't seem to make the buffer type unsigned char.

 [12] Mirtunjay Kumar | 2008-02-26 02:34:47


  it's a very good site of socket programming.I want little help from your side.my problem is that i want to show client Ip at the time of sending some data or connecting to Internet..if you have source code or idia then mail me..
 [13] thiru | 2008-03-05 12:34:29

Your tutorial is very good.

i need one help from you.

one udp server is running in a LAN. This udp server will give response to client as soon as any message is received.

i want to sent message to udp server and then client shoud receive this by using any asynchronous call back event.

main objective is to find UDP server ip from this respons by using call back methods.

please help me
 [14] astha | 2010-02-22 12:32:49

can we block ipaddress using vc++???
if yes then how???
 [15] Daawar Khan | 2010-03-15 14:22:55

Excellent tutorial. It made all the things so easy to understand.
 [16] pandey | 2010-03-16 14:38:18

Hi Daawar..
 [17] St.Juan | 2010-05-28 00:19:21

Thank you very much for this tutorial. I just couldn't find the much better elsewhere.
 [18] Magnum | 2011-01-31 10:27:09

I was having trouble with establishing a UDP server within a normal window application. The callback WMm_SOCKETREAD fits in perfectly. Thanks for talking about the WSAAsyncSelect function.
 [19] Smithc465 | 2014-05-10 10:44:53

I'm seeking weblogs which all have fantastic guidance on what's popular and specifically what the top rated makeup is.. adgeddedeccebbec
 [20] Pharmd348 | 2014-05-11 01:18:25

Very nice site! <a href="http://opeyixa2.com/qovqyo/1.html">cheap goods</a>
 [21] Pharmc865 | 2014-05-11 01:18:42

Very nice site! [url=http://opeyixa2.com/qovqyo/2.html]cheap goods[/url]
 [22] Pharmk484 | 2014-05-11 01:19:03

Very nice site! cheap goods http://opeyixa2.com/qovqyo/4.html
 [23] Pharme100 | 2014-05-11 01:20:41

Very nice site!
 [24] Pharmc650 | 2014-05-12 07:56:28

Very nice site! <a href="http://oixapey2.com/aqsror/1.html">cheap goods</a>
 [25] Pharme449 | 2014-05-12 07:56:55

Very nice site! [url=http://oixapey2.com/aqsror/2.html]cheap goods[/url]
 [26] Pharmk176 | 2014-05-12 13:04:30

Very nice site! <a href="http://oixapey2.com/aqsror/1.html">cheap goods</a>
 [27] Pharmc357 | 2014-05-12 13:08:31

Very nice site! cheap goods http://oixapey2.com/aqsror/4.html
 [28] Pharmb932 | 2014-05-12 13:08:45

Very nice site!
 [29] Pharme477 | 2014-05-13 20:02:11

Very nice site! [url=http://ypxoiea2.com/qyaokq/2.html]cheap goods[/url]
 [30] Pharme468 | 2014-05-13 20:02:27

Very nice site! cheap goods http://ypxoiea2.com/qyaokq/4.html
 [31] Pharme449 | 2014-05-13 20:02:38

Very nice site!
 [32] Pharmd374 | 2014-05-15 02:45:49

Very nice site! <a href="http://apeoixy2.com/tqsrov/1.html">cheap goods</a>
 [33] Pharme82 | 2014-05-15 02:46:17

Very nice site! [url=http://apeoixy2.com/tqsrov/2.html]cheap goods[/url]
 [34] Pharme966 | 2014-05-15 02:46:45

Very nice site! cheap goods http://apeoixy2.com/tqsrov/4.html
 [35] Pharme854 | 2014-05-15 02:47:32

Very nice site!
 [36] Pharmg9 | 2014-05-16 08:35:56

Very nice site! [url=http://aixypeo2.com/ayaoka/2.html]cheap goods[/url]
 [37] Pharmd172 | 2014-05-16 08:36:58

Very nice site! cheap goods http://aixypeo2.com/ayaoka/4.html
 [38] Pharmb402 | 2014-05-16 08:37:37

Very nice site!
 [39] Pharmd118 | 2014-05-17 15:25:47

Very nice site! <a href="http://aieypxo2.com/tovqys/1.html">cheap goods</a>
 [40] Pharme832 | 2014-05-17 15:26:18

Very nice site! [url=http://aieypxo2.com/tovqys/2.html]cheap goods[/url]
 [41] Pharmd725 | 2014-05-17 15:26:37

Very nice site! cheap goods http://aieypxo2.com/tovqys/4.html
 [42] Pharmg353 | 2014-05-17 15:26:51

Very nice site!
 [43] Pharmf422 | 2014-05-18 22:20:40

Very nice site! <a href="http://oieapxy2.com/tyaokt/1.html">cheap goods</a>
 [44] Pharme32 | 2014-05-18 22:23:07

Very nice site! [url=http://oieapxy2.com/tyaokt/2.html]cheap goods[/url]
 [45] Pharmk768 | 2014-05-18 22:23:56

Very nice site! cheap goods http://oieapxy2.com/tyaokt/4.html
 [46] Pharmd369 | 2014-05-18 22:24:32

Very nice site!
 [47] no guarantor loans | 2015-01-13 00:42:10

We've got all types of loans to the UK will meet your every need, we hope!
3 month loans, 3 month payday loans, 6 month loans, no guarantor loans, payday loans no guarantor,

 [48] Corey Xaviers | 2015-03-30 05:27:13

The prime highlight that has profited deal profitable is that you don't have to guarantee any kind of security against the cash asked for by you. Two prime components, at first, your present monetary condition furthermore your repayment limit, are examined by moneylender. http://www.e12monthloan.co.uk/
Comments that will hurt anyone in any way will be deleted.
Don't ask for features, advertise or curse.
If you want to leave a message to the author use the contacts,
if you have any question in relation to your comments please use the forum.
Comments which violate any of these requests will be deleted without further
notice. Use the comment system decently.

Post your comment:
::Top 5 Tutorials::
Embedded Python[105389]
2D Rotated Rectangles Collision Detection[78701]
Keyboard Hook[68403]
HTTP Proxy[35813]

::Top 5 Samples::
2D ColDet Rotated Rectangles[10558]
PS2 Mouse Driver[6060]
Wave Format Player[4945]
Reading FAT12[4827]

All rights reserved to RageStorm © 2009