UDP BASIC Programming for Linux

Source: Internet
Author: User

UDP communication mechanism

Compared to TCP communication, UDP communication is for non-connected communications, so there is no monitoring and connectivity in TCP, etc. involving the connection-oriented process, the main communication process of UDP as shown:


Compared to TCP communication, UDP is relatively simple, although UDP is a non-connected communication, but there is still a server and client points, and the communication of the time directly to specify the other address, ignoring the other party can receive the message you sent. and UDP communication no longer uses Read/write to send messages and read messages, because there is no connection, so you need to specify the address, and read and write do not provide the function of the address, so you need to use alternative methods. The Sendto/recvfrom is used here to ensure that both sides can communicate, and the specifics of the two functions are as follows:

ssize_t sendto (int socket, const void *message, size_t length,int flags, const struct SOCKADDR *dest_addr,socklen_t dest_l EN);/** *  sendto can be used to send messages that are connection-oriented (TCP) and non-connected (UDP). When there is no connection, the address information needs to be provided, and the address information provided is ignored when there is a connection. *  header file      : #include <sys/socket.h> *  socket      : Communication socket * Message     : message content *  length      : Message length *  flags       : Specifies the type of message to be transmitted, using 0 by default. *  dest_addr   : Message Destination Address *  Dest_len    : Address length */ssize_t recvfrom (int socket, void *buffer, size_t length, I NT flags, struct sockaddr *address, socklen_t *address_len),/** *  sendto can be used to receive connection-oriented (TCP) and non-connected (UDP) messages. When there is no connection, the address information needs to be provided, and the address information provided is ignored when there is a connection. *  header file      : #include <sys/socket.h> *  socket      : Communication socket *  buffer      : Message content *  length      : Message length *  flags       : Specifies the type of message to be transmitted, using 0 by default. *  address     : Message destination *  Address_len: Address length */

UDP traffic Sample UDP server

UDP server//singletondemo////Created by Arbboter on 15/1/16.//Copyright (c) 2015 Arbboter. All rights reserved.//#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h># Include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include < Netdb.h> #include <arpa/inet.h>int main (int argc, char **argv) {if (argc! = 2) {printf ("Usage:%s PO        Rt\n ", argv[0]);    Exit (1);    } struct sockaddr_in addr;    addr.sin_family = af_inet;    Addr.sin_port = htons (Atoi (argv[1]));        ADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);    int sock =-1;    Specifies that SOCK_DGRAM represents UDP sock = socket (af_inet, SOCK_DGRAM, 0); if (Sock < 0) {perror ("Create socket failed!        \ n ");    return-1; } if (Bind (sock, (struct sockaddr *) &addr, sizeof (addr)) < 0) {perror ("Bind failed!        \ n ");    Exit (1);    } char buff[512] = {0};    struct sockaddr_in clientaddr; Socklen_tlen = sizeof (CLIENTADDR);    ssize_t ncount = 0;        while (true) {printf ("Waitting for connected...\n"); Blocking data sent over until the client's connection is received ncount = recvfrom (sock, buff, sizeof (buff), 0, (struct sockaddr*) &clientaddr, &len)        ;            if (ncount > 0) {//Receive the message at the same time send back the received buff[ncount] = ' + ';            printf ("[%s:%u],%s\n", Inet_ntoa (CLIENTADDR.SIN_ADDR), Ntohs (clientaddr.sin_port), buff);        SendTo (sock, Buff, ncount, 0, (struct sockaddr *) &clientaddr, sizeof (CLIENTADDR)); } else {perror ("Recvfrom Error!            \ n ");        Break }} return 0;}

UDP client

UDP client//singletondemo////Created by Arbboter on 15/1/16.//Copyright (c) 2015 Arbboter. All rights reserved.//#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h># Include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <  Netdb.h> #include <arpa/inet.h>int main (int argc, char **argv) {if (argc! = 3) {printf ("Usage:%s IP        Port ", argv[0]);    return-1;    } struct sockaddr_in addr;        int sock =-1;    Create a UDP type socket sock = socket (af_inet, SOCK_DGRAM, 0);        if (sock <0) {perror ("Create socket failed!\n");    return-1;    } addr.sin_family = Af_inet;    Addr.sin_port = htons (Atoi (argv[2]));    ADDR.SIN_ADDR.S_ADDR = inet_addr (argv[1]); if (addr.sin_addr.s_addr = = Inaddr_none) {printf ("The server IP address is wrong!")        Please try again ... \ n ");        Close (sock);    return-1;    } char buff[512] = {0};    socklen_t len = sizeof (addr); Ssize_t ncount = 0;        while (1) {printf ("Please enter a message to send:");                scanf ("%s", buff);               Send data directly to a given address, regardless of whether the other person can receive sendto (sock, Buff, strlen (buff), 0, (struct sockaddr *) &addr, sizeof (addr));        len = sizeof (addr);        Wait for the server to return information until it receives data ncount = recvfrom (sock, buff, sizeof (buff), 0, (struct sockaddr *) &addr, &len);            if (ncount > 0) {buff[ncount] = ' + ';        printf ("Server-%s\n", buff);            } else if (ncount = = 0) {printf ("Server closed!\n");            Close (sock);        Break } else {perror ("failed to receive message!            \ n ");            Close (sock);        Break }} return 0;}



UDP BASIC Programming for Linux

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.