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

Sockets in unix
Sockets in unixSockets in unix
Sockets in unixswtjerin4u
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in CDeepak Swain
 
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]RIEleanor McHugh
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using javaUC San Diego
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In JavaAnkur Agrawal
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programmingAnung 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 reportMuragesh Kabbinakantimath
 
Cs423 raw sockets_bw
Cs423 raw sockets_bwCs423 raw sockets_bw
Cs423 raw sockets_bwjktjpc
 
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 RailsEleanor McHugh
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket ProgrammingVipin Yadav
 

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)

Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016Svet Ivantchev
 
tp socket en C.pdf
tp socket en C.pdftp socket en C.pdf
tp socket en C.pdfYoussefJamma
 
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.pptsenthilnathans25
 
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.pptMajedAboubennah
 
Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab FileKandarp Tiwari
 
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
 
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 GoScyllaDB
 
Socket Programming Intro.pptx
Socket  Programming Intro.pptxSocket  Programming Intro.pptx
Socket Programming Intro.pptxssuserc4a497
 
Network programming using python
Network programming using pythonNetwork programming using python
Network programming using pythonAli Nezhad
 
Linux Serial Driver
Linux Serial DriverLinux Serial Driver
Linux Serial Driver艾鍗科技
 
OpenSSL Basic Function Call Flow
OpenSSL Basic Function Call FlowOpenSSL Basic Function Call Flow
OpenSSL Basic Function Call FlowWilliam Lee
 

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

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 

Recently uploaded (20)

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 

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.