--socket programming based on UDP protocol

Source: Internet
Author: User
Tags htons

One. Socket API

The previous article "--socket Programming based on TCP protocol" http://2627lounuo.blog.51cto.com/10696599/1775559 has spent a lot of time talking about sockets and using basic sockets API needs to be aware of the problem, here will not repeat it. The following is mainly about UDP and TCP in the socket programming differences;


1. Create sock

and TCP connection-oriented reliable byte stream service is different,UDP is a non-connected unreliable datagram transmission service , although different, but also in the process of communication between the need to provide a socket interface for data transmission, The first step is still to create a socket:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/80/6F/wKiom1dBZUHxHpYSAAAKvAjZsU4304.png "title=" Socket.png "alt=" Wkiom1dbzuhxhpysaaakvajzsu4304.png "/>

function parameters,

domain is the type of protocol used at the bottom, and here is still af_inet representative IPv4;

The type is here because UDP is based on datagram, so it is sock_dgram;

protocol is 0because the first two parameters already know what the protocol is;


2. Binding

Although it is a non-connected transport service, but the required network information is not limited, so still need to have the local network address information struct SOCKADDR_IN structure type to store, but also need to create a socket to bind the connection:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/80/6D/wKioL1dBZ-yiC1jwAAAMZ6E489s709.png "style=" float: none; "title=" Bind.png "alt=" Wkiol1dbz-yic1jwaaamz6e489s709.png "/>

function parameters,

SOCKFD is the created socket descriptor;

The addr is the address of the following structure body;

Addrlen is a structural body size;

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/80/6D/wKioL1dBZ_6SJZCYAAAhDpDPuvw435.png "style=" float: none; "title=" Sockaddr_in.png "alt=" Wkiol1dbz_6sjzcyaaahdpdpuvw435.png "/>

Structure,

Sin_family is the protocol used at the bottom, and the first parameter in the socket is the same as af_inet;

Sin_port for the specified port number, here is the need for network byte-order conversion, details in the TCP of the narrative;

Sin_addr is also a struct, where the member should be the specified IP address;

650) this.width=650; "src=" http://s2.51cto.com/wyfs02/M00/80/6F/wKiom1dBaCHQyDhVAAAJdITNPv8574.png "title=" struct In_addr.png "alt=" Wkiom1dbachqydhvaaajditnpv8574.png "/>


3. Receiving data

It is because of the characteristics of UDP, so in the UDP connection transmission data is not necessary to the network connection request to listen, also do not need to accept processing connection, here after binding the socket and local information, for the server can be directly to the data received, The function used is recvfrom:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/80/6D/wKioL1dBbUzjR51-AAATeN63lrg121.png "title=" Recvfrom.png "alt=" Wkiol1dbbuzjr51-aaaten63lrg121.png "/>

function parameters,

SOCKFD is the created socket descriptor;

buf is a buffer that holds the data received;

Len is the size of the length of the received datagram at one time;

flags is a flag-bit attribute that, when set to 0 , represents a blocked type to receive;

src_addr represents the network address information of the party sending the data;

Addrlen is a length information of Src_len;

The function failed to return 1 and the corresponding size was successfully returned with the error code;


4. Send data

For the client, because it is a UDP transmission, so there is no need to make a connection request, when the good one socket and destination network address information is created, you can send the data directly:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/80/6D/wKioL1dBdcLAKlyQAAATQqhc1xU759.png "title=" Sendto.png "alt=" Wkiol1dbdclaklyqaaatqqhc1xu759.png "/>

function parameters,

SOCKFD is the created socket descriptor;

buf is the data buffer to be sent;

Len is the length of the data being sent;

The flags are set to 0 to indicate the default state;

dest_addr is the network address information structure of the destination terminal;

Addrlen is the length size of dest_addr;


Two. Chestnut time

It is because of the non-reliability of UDP, it is more convenient to use than TCP, because UDP does not need to maintain connection and error verification, you can also use the socket API above to design server-side and client data transfer:


Server-Side design:

#include  <stdio.h> #include  <stdlib.h> #include  <string.h> #include  <sys /types.h> #include  <sys/socket.h> #include  <netinet/in.h>void usage (const  CHAR&NBSP;*ARGV)//Parameter error to determine {    printf ("%s   [ip]   [port]\n", &NBSP;ARGV);     exit (0);} Int create_server_sock (Int ip, int port)//Create server-side Socket{    int  sock = socket (af_inet, sock_dgram, 0);     if (sock <  0)     {        perror ("socket");         exit (1);    }    struct  sockaddr_in server;//Creating server-side network address information     server.sin_family = AF_INET;     server.sin_port = htons (port);     server.sin_adDr.s_addr = ip;    if (Bind (sock,  (struct sockaddr*) &server,  sizeof (server))  < 0)//Binding     {         Perror ("bind");         exit (2);    }     return sock;} Int main (int argc, char *argv[]) {    if (argc != 3)          usage (argv[0]);    int port =  Atoi (argv[2]);     int ip = inet_addr (argv[1]);     int  server_sock = create_server_sock (Ip, port);    char buf[1024];     struct sockaddr_in client;    socklen_t len =  sizeof (client);     while (1)     {    //readFetch data         memset (buf,  ',  sizeof (BUF));         ssize_t size = recvfrom (server_sock, buf, sizeof (BUF)-1 , 0,  (struct sockaddr*) &client, &len);         if (size < 0)             perror ( "Recvfrom");         printf ("client [%s] [%d]# %s\n",  inet_ntoa (CLIENT.SIN_ADDR),  ntohs (Client.sin_port),  buf);    }     return 0;}


Client design:

#include  <stdio.h> #include  <stdlib.h> #include  <string.h> #include  <sys /types.h> #include  <sys/socket.h> #include  <netinet/in.h>void usage (const  CHAR&NBSP;*ARGV)//the same parameter error judgment {    printf ("%s   [ip]   [port]\ n ");     exit (0);} Int main (int argc, char *argv[]) {    if (argc != 3)          usage (argv[0]);    int port =  Atoi (argv[2]);     int ip = inet_addr (argv[1]);     int  client_sock = socket (af_inet, sock_dgram, 0);  //Create client Side socket     if (client_sock < 0)     {            perror ("socket");         exit (1);     }       struct sockaddr_in server;// Create the destination server-side network address information     server.sin_family = AF_INET;     Server.sin_port = htons (port);    server.sin_addr.s_addr = ip;      char buf[1024];    while (1)     {            memset (buf,  ',  sizeof (BUF));         printf ("client# ");         fflush (stdout);         gets (BUF);         //Send Data         ssize_t size = sendto ( Client_sock, buf, sizeof (BUF), 0,  (struct sockaddr*) &server, sizeof (server)) ;      &nbSp;  if (size < 0)              perror ("SendTo");     }    return 0;}


To run the program:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/80/70/wKiom1dBfXWzEWh_AAAH8RJM1gM326.png "style=" float: none; "title=" Udp.png "alt=" Wkiom1dbfxwzewh_aaah8rjm1gm326.png "/>


Because UDP is not connected, so the client and server side to each other is non-interference, that is, regardless of which side of the two sides closed, the other side can also do the corresponding operation, but the other side cannot respond or deal with it.


Three. Port number

The server-side program above is run with a custom port number, and the client side is not bound to its port number, which is randomly assigned by the system, so what is the port number in the system?

We know that in TCP messages there is a 16-bit source port number and a destination port number, so the port number should be from 0 to 2 16 square-1, which is 0~65535, where:

    1. recognized ports (well known Ports): from 0 to 1023, this type of port is often referred to as a common port, and they are tightly bound (binding) to certain services. Usually the communication of these ports clearly indicates the protocol of a certain service. For example: Port 80 is actually always HTTP traffic, and Port 23rd is dedicated to the Telnet service;

    2. Register port (registered Ports): from 1024 to 49151. They are loosely tied to some services. This means that there are many services bound to these ports, which are also used for many other purposes, most of which do not explicitly define the service object, and different programs can be defined on their own. For example: Many systems handle dynamic ports starting around 1024,

    3. dynamic or private port (and/or private Ports): from 49152 to 65535. In theory, these ports should not be assigned to the service. In fact, some of the more special programs, especially some Trojan horse programs like to use these ports, because these ports are often not attracted attention, easy to hide;


any TCP/IP implementation provides services that are port numbers between 1-1023, which are managed by the IANA distribution. Where the port number below 255 is reserved for public applications, the 255 to 1023 port numbers are assigned to individual companies for special applications, and for port numbers above 1023, called temporary port numbers, the IANA does not make provisions.

The common reserved TCP port numbers are:

HTTP 80,ftp 20/21,telnet 23,smtp 25,dns 53 and so on.

The commonly used reserved UDP port numbers are:

DNS 53,BOOTP (server)/(client), TFTP 69,SNMP 161, etc.


Different port numbers can be divided into different lines depending on the number of previous segments, for example:

8 Series Port Meaning

PORT: 80

Service: HTTP

Description: Used for web browsing. Trojan Executor open this port.

8080 ports

Port Description: 8080 port with 80 port, is used for WWW Proxy service, can implement web browsing, often when visiting a website or using a proxy server, will be added ": 8080" port number.

Port vulnerability: port 8080 can be exploited by a variety of virus programs, such as the brown Orifice (BrO) Trojan Horse virus can use 8080 port fully remote control infected computer. In addition, the Remoconchubo,ringzero Trojan can also use this port for attack.

Operation suggestions: Generally we use 80 port for web browsing, in order to avoid the virus attack, we can close the port.



Finish

This article is from the "Knock Code good Sleep zzz" blog, please be sure to keep this source http://2627lounuo.blog.51cto.com/10696599/1775959

--socket programming based on UDP protocol

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.