Home
Tutorials
Code Snippets
Code Samples
Downloads
Links

The Blog
Our Projects
About
Contact

::Add RageStorm to Favorites!::

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

 
Tutorial - UDP
Author:Arkon
Category:Internet & Networks
Uploaded at:29-May-03
Views:65767
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;

WSADATA data;

// 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).
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
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("127.0.0.1"); // 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..

SOCKADDR from;
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...

closesocket(sock);
WSACleanup();

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(13)
 [1] Aaron J. | 2006-02-09 22:46:50

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

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

This tutorial is awesome :D It makes networking so simple :D Thanks a bunch for posting this!!
 [4] Kris | 2006-08-31 23: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("127.0.0.1"); // IP to communicate with.

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

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

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

Thanks for a v. good tutorial!!

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

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

hello,

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.

Thanks
MM

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)        
        }break;
 [10] Arun Gite | 2007-07-25 07:28:11

Hi friends,
  This UDP tutorial is really good for those are new to UDP Socket Programming.
  Thanking you
Regards,
Arun Gite
 [11] Wei Min | 2007-12-21 08: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 07:34:47

Hi

  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 17: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
NOTE:
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:
Name:
email:
Comment:
::Top 5 Tutorials::
Embedded Python[116799]
2D Rotated Rectangles Collision Detection[88709]
Keyboard Hook[77096]
UDP[65767]
HTTP Proxy[41155]

::Top 5 Samples::
2D ColDet Rotated Rectangles[11549]
PS2 Mouse Driver[6946]
Wave Format Player[5780]
Reading FAT12[5607]
CodeGuru[5346]


All rights reserved to RageStorm © 2009