SlideShare a Scribd company logo
1 of 7
UDP Socket 
Programming 
in C
UDP sockets 
This article describes how to write a simple echo server and client using udp sockets in C 
on Linux/Unix platform. UDP sockets or Datagram sockets are different from the TCP 
sockets in a number of ways. The most important difference is that UDP sockets are not 
connection oriented. More technically speaking, a UDP server does notaccept connections 
and a udp client does not connect to server. 
The server will bind and then directly receive data and the client shall directly send the data. 
ECHO Server 
So lets first make a very simple ECHO server with UDP socket. The flow of the code would 
be 
socket() -> bind() -> recvfrom() -> sendto() 
C code 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
/* 
Simple udp server 
Silver Moon (m00n.silv3r@gmail.com) 
*/ 
#include<stdio.h> //printf 
#include<string.h> //memset 
#include<stdlib.h> //exit(0); 
#include<arpa/inet.h> 
#include<sys/socket.h> 
#define BUFLEN 512 //Max length of buffer 
#define PORT 8888 //The port on which to listen for incoming data 
void die(char *s) 
{ 
perror(s); 
exit(1); 
} 
int main(void) 
{ 
struct sockaddr_in si_me, si_other; 
int s, i, slen = sizeof(si_other) , recv_len; 
char buf[BUFLEN]; 
//create a UDP socket 
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) 
{ 
die("socket"); 
}
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
// zero out the structure 
memset((char *) &si_me, 0, sizeof(si_me)); 
si_me.sin_family = AF_INET; 
si_me.sin_port = htons(PORT); 
si_me.sin_addr.s_addr = htonl(INADDR_ANY); 
//bind socket to port 
if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1) 
{ 
die("bind"); 
} 
//keep listening for data 
while(1) 
{ 
printf("Waiting for data..."); 
fflush(stdout); 
//try to receive some data, this is a blocking call 
if ((recv_len=recvfrom(s, buf, BUFLEN, 0,(struct sockaddr *) &si_other, &slen))== -1) 
{ 
die("recvfrom()"); 
} 
//print details of the client/peer and the data received 
printf("Received packet from %s:%dn", inet_ntoa(si_other.sin_addr), 
ntohs(si_other.sin_port)); 
printf("Data: %sn" , buf); 
//now reply the client with the same data 
if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == -1) 
{ 
die("sendto()"); 
} 
} 
close(s); 
return 0; 
} 
Run the above code by doing a gcc server.c && ./a.out at the terminal. Then it will show 
waiting for data like this 
$ gcc server.c && ./a.out 
Waiting for data... 
Next step would be to connect to this server using a client. We shall be making a client 
program a little later but first for testing this code we can use netcat.
Open another terminal and connect to this udp server using netcat and then send some 
data. The same data will be send back by the server. Over here we are using the ncat 
command from the nmap package. 
$ ncat -vv localhost 8888 -u 
Ncat: Version 5.21 ( http://nmap.org/ncat ) 
Ncat: Connected to 127.0.0.1:8888. 
hello 
hello 
world 
world 
Note : We had to use netcat because the ordinary telnet command does not support udp 
protocol. The -u option of netcat specifies udp protocol. 
The netstat command can be used to check if the udp port is open or not. 
$ netstat -u -a 
Active Internet connections (servers and established) 
Proto Recv-Q Send-Q Local Address Foreign Address State 
udp 0 0 localhost:11211 *:* 
udp 0 0 localhost:domain *:* 
udp 0 0 localhost:45286 localhost:8888 
ESTABLISHED 
udp 0 0 *:33320 *:* 
udp 0 0 *:ipp *:* 
udp 0 0 *:8888 *:* 
udp 0 0 *:17500 *:* 
udp 0 0 *:mdns *:* 
udp 0 0 localhost:54747 localhost:54747 
ESTABLISHED 
udp6 0 0 [::]:60439 [::]:* 
udp6 0 0 [::]:mdns [::]:*
Note the *:8888 entry of output. Thats our server program. 
The entry that has localhost:8888 in "Foreign Address" column, indicates some client 
connected to it, which is netcat over here. 
Client 
Now that we have tested our server with netcat, its time to make a client and use it instead 
of netcat. 
The program flow is like 
socket() -> sendto()/recvfrom() 
Here is a quick example 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
/* 
Simple udp client 
Silver Moon (m00n.silv3r@gmail.com) 
*/ 
#include<stdio.h> //printf 
#include<string.h> //memset 
#include<stdlib.h> //exit(0); 
#include<arpa/inet.h> 
#include<sys/socket.h> 
#define SERVER "127.0.0.1" 
#define BUFLEN 512 //Max length of buffer 
#define PORT 8888 //The port on which to send data 
void die(char *s) 
{ 
perror(s); 
exit(1); 
} 
int main(void) 
{ 
struct sockaddr_in si_other; 
int s, i, slen=sizeof(si_other); 
char buf[BUFLEN]; 
char message[BUFLEN]; 
if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) 
{ 
die("socket"); 
} 
memset((char *) &si_other, 0, sizeof(si_other)); 
si_other.sin_family = AF_INET; 
si_other.sin_port = htons(PORT);
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
if (inet_aton(SERVER , &si_other.sin_addr) == 0) 
{ 
fprintf(stderr, "inet_aton() failedn"); 
exit(1); 
} 
while(1) 
{ 
printf("Enter message : "); 
gets(message); 
//send the message 
if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen)==-{ 
die("sendto()"); 
} 
//receive a reply and print it 
//clear the buffer by filling null, it might have previously received data 
memset(buf,'0', BUFLEN); 
//try to receive some data, this is a blocking call 
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1) 
{ 
die("recvfrom()"); 
} 
puts(buf); 
} 
close(s); 
return 0; 
} 
Run the above program and it will ask for some message 
$ gcc client.c -o client && ./client 
Enter message : happy 
happy 
Whatever message the client sends to server, the same comes back as it is and is echoed. 
Conclusion 
UDP sockets are used by protocols like DNS etc. The main idea behind using UDP is to 
transfer small amounts of data and where reliability is not a very important issue. UDP is 
also used in broadcasting/multicasting.
When a file transfer is being done or large amount of data is being transferred in parts the 
transfer has to be much more reliable for the task to complete. Then the TCP sockets are 
used.

More Related Content

What's hot

Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
Deepak Swain
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
Anung Ariwibowo
 
Error Control in Multimedia Communications using Wireless Sensor Networks report
Error Control in Multimedia Communications using Wireless Sensor Networks reportError Control in Multimedia Communications using Wireless Sensor Networks report
Error Control in Multimedia Communications using Wireless Sensor Networks report
Muragesh Kabbinakantimath
 
Cs423 raw sockets_bw
Cs423 raw sockets_bwCs423 raw sockets_bw
Cs423 raw sockets_bw
jktjpc
 

What's hot (20)

Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
Socket programming in c
Socket programming in cSocket programming in c
Socket programming in c
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
 
Java sockets
Java socketsJava sockets
Java sockets
 
Socket programing
Socket programingSocket programing
Socket programing
 
Sockets intro
Sockets introSockets intro
Sockets intro
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIThe Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
 
#1 (TCPvs. UDP)
#1 (TCPvs. UDP)#1 (TCPvs. UDP)
#1 (TCPvs. UDP)
 
Lab
LabLab
Lab
 
Tcp sockets
Tcp socketsTcp sockets
Tcp sockets
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using java
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
Error Control in Multimedia Communications using Wireless Sensor Networks report
Error Control in Multimedia Communications using Wireless Sensor Networks reportError Control in Multimedia Communications using Wireless Sensor Networks report
Error Control in Multimedia Communications using Wireless Sensor Networks report
 
Cs423 raw sockets_bw
Cs423 raw sockets_bwCs423 raw sockets_bw
Cs423 raw sockets_bw
 
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsAnchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
 
Sockets
SocketsSockets
Sockets
 
Whispered secrets
Whispered secretsWhispered secrets
Whispered secrets
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 

Similar to Udp socket programming(Florian)

Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)
Youssef Dirani
 
Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)
Youssef Dirani
 

Similar to Udp socket programming(Florian) (20)

Basics of sockets
Basics of socketsBasics of sockets
Basics of sockets
 
Computer networkppt4577
Computer networkppt4577Computer networkppt4577
Computer networkppt4577
 
Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016
 
Npc14
Npc14Npc14
Npc14
 
tp socket en C.pdf
tp socket en C.pdftp socket en C.pdf
tp socket en C.pdf
 
sockets_intro.ppt
sockets_intro.pptsockets_intro.ppt
sockets_intro.ppt
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
 
Introduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.pptIntroduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.ppt
 
Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab File
 
Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)
 
Dns server clients (actual program)
Dns server clients (actual program)Dns server clients (actual program)
Dns server clients (actual program)
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in GoCapturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
 
Sockets
SocketsSockets
Sockets
 
Socket Programming Intro.pptx
Socket  Programming Intro.pptxSocket  Programming Intro.pptx
Socket Programming Intro.pptx
 
Network programming using python
Network programming using pythonNetwork programming using python
Network programming using python
 
L5-Sockets.pptx
L5-Sockets.pptxL5-Sockets.pptx
L5-Sockets.pptx
 
Linux Serial Driver
Linux Serial DriverLinux Serial Driver
Linux Serial Driver
 
Arp
ArpArp
Arp
 
OpenSSL Basic Function Call Flow
OpenSSL Basic Function Call FlowOpenSSL Basic Function Call Flow
OpenSSL Basic Function Call Flow
 

Recently uploaded

Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
chumtiyababu
 

Recently uploaded (20)

Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 

Udp socket programming(Florian)

  • 2. UDP sockets This article describes how to write a simple echo server and client using udp sockets in C on Linux/Unix platform. UDP sockets or Datagram sockets are different from the TCP sockets in a number of ways. The most important difference is that UDP sockets are not connection oriented. More technically speaking, a UDP server does notaccept connections and a udp client does not connect to server. The server will bind and then directly receive data and the client shall directly send the data. ECHO Server So lets first make a very simple ECHO server with UDP socket. The flow of the code would be socket() -> bind() -> recvfrom() -> sendto() C code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 /* Simple udp server Silver Moon (m00n.silv3r@gmail.com) */ #include<stdio.h> //printf #include<string.h> //memset #include<stdlib.h> //exit(0); #include<arpa/inet.h> #include<sys/socket.h> #define BUFLEN 512 //Max length of buffer #define PORT 8888 //The port on which to listen for incoming data void die(char *s) { perror(s); exit(1); } int main(void) { struct sockaddr_in si_me, si_other; int s, i, slen = sizeof(si_other) , recv_len; char buf[BUFLEN]; //create a UDP socket if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { die("socket"); }
  • 3. 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 // zero out the structure memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); //bind socket to port if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1) { die("bind"); } //keep listening for data while(1) { printf("Waiting for data..."); fflush(stdout); //try to receive some data, this is a blocking call if ((recv_len=recvfrom(s, buf, BUFLEN, 0,(struct sockaddr *) &si_other, &slen))== -1) { die("recvfrom()"); } //print details of the client/peer and the data received printf("Received packet from %s:%dn", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); printf("Data: %sn" , buf); //now reply the client with the same data if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == -1) { die("sendto()"); } } close(s); return 0; } Run the above code by doing a gcc server.c && ./a.out at the terminal. Then it will show waiting for data like this $ gcc server.c && ./a.out Waiting for data... Next step would be to connect to this server using a client. We shall be making a client program a little later but first for testing this code we can use netcat.
  • 4. Open another terminal and connect to this udp server using netcat and then send some data. The same data will be send back by the server. Over here we are using the ncat command from the nmap package. $ ncat -vv localhost 8888 -u Ncat: Version 5.21 ( http://nmap.org/ncat ) Ncat: Connected to 127.0.0.1:8888. hello hello world world Note : We had to use netcat because the ordinary telnet command does not support udp protocol. The -u option of netcat specifies udp protocol. The netstat command can be used to check if the udp port is open or not. $ netstat -u -a Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State udp 0 0 localhost:11211 *:* udp 0 0 localhost:domain *:* udp 0 0 localhost:45286 localhost:8888 ESTABLISHED udp 0 0 *:33320 *:* udp 0 0 *:ipp *:* udp 0 0 *:8888 *:* udp 0 0 *:17500 *:* udp 0 0 *:mdns *:* udp 0 0 localhost:54747 localhost:54747 ESTABLISHED udp6 0 0 [::]:60439 [::]:* udp6 0 0 [::]:mdns [::]:*
  • 5. Note the *:8888 entry of output. Thats our server program. The entry that has localhost:8888 in "Foreign Address" column, indicates some client connected to it, which is netcat over here. Client Now that we have tested our server with netcat, its time to make a client and use it instead of netcat. The program flow is like socket() -> sendto()/recvfrom() Here is a quick example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 /* Simple udp client Silver Moon (m00n.silv3r@gmail.com) */ #include<stdio.h> //printf #include<string.h> //memset #include<stdlib.h> //exit(0); #include<arpa/inet.h> #include<sys/socket.h> #define SERVER "127.0.0.1" #define BUFLEN 512 //Max length of buffer #define PORT 8888 //The port on which to send data void die(char *s) { perror(s); exit(1); } int main(void) { struct sockaddr_in si_other; int s, i, slen=sizeof(si_other); char buf[BUFLEN]; char message[BUFLEN]; if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { die("socket"); } memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT);
  • 6. 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 if (inet_aton(SERVER , &si_other.sin_addr) == 0) { fprintf(stderr, "inet_aton() failedn"); exit(1); } while(1) { printf("Enter message : "); gets(message); //send the message if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen)==-{ die("sendto()"); } //receive a reply and print it //clear the buffer by filling null, it might have previously received data memset(buf,'0', BUFLEN); //try to receive some data, this is a blocking call if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1) { die("recvfrom()"); } puts(buf); } close(s); return 0; } Run the above program and it will ask for some message $ gcc client.c -o client && ./client Enter message : happy happy Whatever message the client sends to server, the same comes back as it is and is echoed. Conclusion UDP sockets are used by protocols like DNS etc. The main idea behind using UDP is to transfer small amounts of data and where reliability is not a very important issue. UDP is also used in broadcasting/multicasting.
  • 7. When a file transfer is being done or large amount of data is being transferred in parts the transfer has to be much more reliable for the task to complete. Then the TCP sockets are used.