Linux Network Programming--UDP programming

Source: Internet
Author: User
Tags server port htons

Overview

UDP is the abbreviation of user Datagram Protocol, the Chinese name is the Subscriber datagram Protocol, it is a simple Transport layer protocol for datagram, and it is a kind of non-connected protocol for processing packets in the network. UDP does not provide reliable transmission, it simply sends the application to the IP layer's datagram, but does not guarantee that it will reach its destination. Because UDP does not have to establish a connection between the client and the server before transmitting the datagram, and there is no mechanism such as time-out retransmission, the transmission speed is very fast.


UDP has the following characteristics:

1) Abstraction of the mail system service pattern ( can be compared by mail model )

2) Each group carries a complete destination address

3) Do not need to establish a link before sending data

4) Do not check the order of the packets, The order of grouping cannot be guaranteed

5) Recovery and retransmission without grouping errors

6) does not guarantee the reliability of data transmission



In the network quality is very dissatisfied with the environment, UDP Protocol packet loss will be more serious. However, due to the characteristics of UDP: it does not belong to the connection protocol, thus has the advantage of small resource consumption, processing speed, so usually audio, video and ordinary data in the transfer of UDP more, because they even occasionally lost one or two packets, will not have a large impact on the reception results. For example, we chat with ICQ and QQ is the use of UDP protocol.


c/S architecture for UDP programming



UDP client programcompared to the letter model, the client is equivalent to the sender, in order to successfully send a letter, the envelope must be written on each other's address.

ssize_t sendto (int sockfd,

const void *BUF,

size_t Nbytes,

int flags,

const struct SOCKADDR *to,

Socklen_t Addrlen);

features :

Sends UDP data to the IP specified in the to struct pointer, and can send a 0-length UDP packet

Parameters :

SOCKFD: Socket

buf: Send data buffer

nbytes: The size of the Send data buffer

flags: typically 0

to: A pointer to the destination host address structure body

Addrlen: The length of the content to which to point

return value :

Success: Length of data sent

Failed:-1


Here, the network debugging assistant downloads via the Windows Network debugging assistant and the Ubuntu client program in the virtual machine, click here.


The network debugging assistant for Windows receives the client's request as a server, and the Debug Assistant is configured as follows:



The UDP client program for Ubuntu in the virtual machine:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys /socket.h> #include <netinet/in.h> #include <arpa/inet.h>int main (int argc, char *argv[]) {unsigned short Port = 8080;//Server Port char *server_ip = "10.221.20.10";//server IP address if (argc > 1)//main function parameter, server IP address {server_ip = argv[1];} if (argc > 2)//main function pass parameter, server port {port = atoi (Argv[2]);}   int SOCKFD;SOCKFD = socket (af_inet, SOCK_DGRAM, 0); Create a UDP socket if (SOCKFD < 0) {perror ("socket"); exit (-1);} Socket address struct sockaddr_in dest_addr;bzero (&dest_addr, sizeof (DEST_ADDR));//empty content dest_addr.sin_family = af_inet;/ /Ipv4dest_addr.sin_port = htons (port),//Ports conversion Inet_pton (Af_inet, server_ip, &dest_addr.sin_addr);//IP Address conversion printf ( "Send data to UDP server%s:%d!\n", SERVER_IP, Port) and while (1) {char send_buf[512] = ""; fgets (Send_buf, sizeof (SEND_BUF), St DIN);//Get Input Send_buf[strlen (SEND_BUF)-1] = ' send_buf ';//send data int len = sendto (SOCKFD, strlen, Send_buf (), 0, (struct Sockaddr*) &dest_addr, sizeof (DEST_ADDR));p rintf ("len =%d\n", len);} Close (SOCKFD); return 0;}


The results of the operation are as follows:


UDP client Note points :

1) Local IP, local port (who am I)

2) Destination IP, Destination port (issued to whom)

3) in the client's code, we only set the destination IP, destination port

4) The client's local IP, local port is when we call SendTo, the Linux system is automatically assigned to the client at the bottom, the allocation of the port is randomly allocated, that is, each time the system to the port is different.


UDP Server program

What are the requirements for UDP network programs to collect data?

1) Determine the IP address

2) determine the port (ports)

This is just like, I want to receive a letter from someone else, I have to tell someone my address (IP), and also tell someone about my apartment box number (port).


The receiving end uses the bind () function to complete the binding of the address structure to the socket socket, so that the IP, port is fixed, the sender in the SendTo function to specify the receiver IP, port, you can send data.


header files required : #include <sys/socket.h>

int bind (int sockfd,

const struct SOCKADDR *myaddr,

Socklen_t Addrlen);

features :

Bind the local protocol address with SOCKFD so that the IP, port is fixed

Parameters :

SOCKFD: Socket socket

myaddr: A pointer to an address structure that points to a specific protocol

Addrlen: The length of the address structure

return value :

Success: return 0

Failed:-1


Examples of usage are as follows:

Local network address struct sockaddr_in my_addr;bzero (&my_addr, sizeof (MY_ADDR));//empty structure contents my_addr.sin_family = af_inet;// Ipv4my_addr.sin_port   = htons (port);//Ports Conversion my_addr.sin_addr.s_addr = HTONL (inaddr_any);//bind NIC all IP addresses, inaddr_ Any is a wildcard address with a value of 0printf ("Binding Server to Port%d\n", port), int err_log;err_log = bind (SOCKFD, (struct sockaddr*) &my_ addr, sizeof (MY_ADDR)); Bind if (Err_log! = 0) {perror ("bind"); Close (SOCKFD); exit (-1);}

Binding port There are some issues to be aware of, see the binding (BIND) port needs attention.


ssize_t recvfrom (int sockfd, void *buf,

size_t Nbytes,int Flags,

struct SOCKADDR *from,

Socklen_t *addrlen);

features :

Receives UDP data and stores the source address information in the from-point structure

Parameters :

sockfd : socket

buf : Receive data buffer

nbytes : receive data buffer size

flags : socket flag

from : source address struct pointer, which is used to hold the source of the data

addrlen : The length of the content referred to from

return value :

Success: Received length

Failed:-1


The server programs in Ubuntu are as follows:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys /socket.h> #include <netinet/in.h> #include <arpa/inet.h>int main (int argc, char *argv[]) {unsigned short Port = 8000;//Local Port if (argc > 1) {port = atoi (Argv[1]);} int SOCKFD;SOCKFD = socket (af_inet, SOCK_DGRAM, 0);//Create Socket if (SOCKFD < 0) {perror ("socket"); exit (-1);} Local network address struct sockaddr_in my_addr;bzero (&my_addr, sizeof (MY_ADDR));//empty structure contents my_addr.sin_family = af_inet;// Ipv4my_addr.sin_port = htons (port);//Port Conversion my_addr.sin_addr.s_addr = htonl (Inaddr_any); Bind network card All IP addresses, Inaddr_any is a wildcard address, value is 0printf ("Binding Server to Port%d\n", port), int err_log;err_log = bind (SOCKFD, struct s ockaddr*) &my_addr, sizeof (MY_ADDR)); Bind if (Err_log! = 0) {perror ("bind"); Close (SOCKFD); exit (-1);} printf ("Receive data...\n"); while (1) {int Recv_len;char recv_buf[512] = ""; struct sockaddr_in Client_addr;char cli_ip[ Inet_addrstrlen] = "";//inet_addrstrlen=16socklen_t Cliaddr_len = sizeof (CLIENT_ADDR); Accept Data Recv_len = Recvfrom (sockfd, Recv_buf, sizeof (RECV_BUF), 0, (struct sockaddr*) &client_addr, &cliaddr_len) ; Inet_ntop (Af_inet, &client_addr.sin_addr, Cli_ip, Inet_addrstrlen);p rintf ("\nip:%s, port:%d\n", Cli_ip, Ntohs ( Client_addr.sin_port));p rintf ("Data (%d):%s\n", recv_len,recv_buf);} Close (SOCKFD); return 0;}

The network debugging assistant for Windows sends data to a server in Ubuntu as a client, and the Debug Assistant is configured as follows:



The results of the operation are as follows:



Sample code download please click here.

Linux Network Programming--UDP programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.