Linux Learning four: UDP programming (top)

Source: Internet
Author: User
Tags function definition sin sprintf htons

About UDP vs. TCP versus suboptimal, this is not the point.
The functions that are used in UDP code are very similar to those used for TCP, mainly because the set of interface libraries adds a layer of abstraction to the underlying TCP and UDP functions, which makes programming easier, but loses some control.
The only real difference between the two function calls is a parameter to the Soceket function call, TCP is SOCK_STREAM,UDP Sock_dgram, both can use the Recvfrom function, and recv is used only for TCP.
Of course, the function changes are not so simple, because you have to move from a connected protocol to a non-connected protocol.
Here is a simple and straightforward UDP application to understand the process. Implement a program that initiates the transmission of messages to a port on another system, which does not have a handshake mechanism and is unsure whether another system is listening, accepting, or processing data.
  Sender :sender, send a text message, and then send a termination message (tell the receiver to send complete).

The general steps for UDP programming clients are:

1, create a socket, with a function socket ();
2, set the socket properties, with the function setsockopt (); * Optional
3, binding IP address, port and other information to the socket, with the function bind (); * Optional
4, set the other IP address and port properties;
5, send data, with function sendto ();
6, close the network connection;
SENDER.C:
#include "stdio.h" can only be used "" to indicate that,< is not displayed.

       #include   "stdlib.h"
      # include  "String.h"
       #include "sys/socket.h"
        #include "netinet/in.h"
       #include "arpa/inet.h"
       #include "netdb.h"
int port=6789;

      void Main ()
         {
           int socket_descriptor;//define socket Descriptor
           int i=0;
           char buf[120];//Set buffer
            struct sockaddr_in address;//Processing network communication address, put like xxx.xxx.xxx.xxx decimal

//IP address conversion is a 32-bit integer, the failure returns Inaddr_none

initializing the Internet Protocol socket address structure
Bzero (&address,sizeof (address));//Empty data structure
Address.sin_family=af_inet;
ADDRESS.SIN_ADDR.S_ADDR=INET_ADDR ("127.0.0.1");//Set the IP address function of the server

address.sin_port=htons (port); //Set port

Create a UDP socket
Socket_descriptor=socket (af_inet,sock_sgram,0);


Send data in a loop
for (i=0;i<120;i++)
{
sprintf (BUF, "Data packet with ID%d\n", i);
SendTo (Socket_descriptor,buf,sizeof (BUF), 0,
(struct sockaddr *) &address,sizeof (address));
}

Send a termination message
sprintf (buf, "stop\n");
SendTo (Socket_descriptor,buf,sizeof (BUF), 0,
(struct sockaddr *) &address,sizeof (address));

Shut down the network
Close (Socket_descriptor);
printf ("Message sent,terminating\n");

Exit (0);
}
Specific detailed comments under:

First, the library file:

Stdlib.h: Contains the most commonly used system functions for C, C + +, and defines five types, some macros, and common tool functions.

Common functions such as malloc (), Calloc (), realloc (), free (), ystem (), Atoi (), ATOL (), Rand (),

Srand (), exit (), etc.

String.h: header file for function definition of character array, common functions are strlen, strcmp, strcpy, etc.

Sys/socket.h: Provides socket functions and data structures

Netinet/in.h: Define data structure sockaddr_in, Internet address family

Arpa/inet.h: provides IP address translation functions

Netdb.h: Provides functions for setting and retrieving domain names

Then look at the functions involved:

struct SOCKADDR is a universal socket address, while struct sockaddr_in is the address form of a socket in an Internet environment .

The same length are 16 bytes. The two are parallel structures, and pointers to sockaddr_in structures can also point to sockaddr. Under normal circumstances,

The SOCKADDR_IN structure needs to be cast into the SOCKADDR structure and then passed into the system call function.

inet_addr is replaced by Inet_aton under Linux. function is to convert a string as a parameter into a the one that can be used internally

An integer that is an Internet address.

The htons function handles different systems for internal data representation, which matches your host byte order and network byte order.

Socket function Create Socket: 0 represents the default socket function, request a communication port to the system Sock_dgram by default using UDP
When calling the socket function:

UDP uses Sock_sgram,

Tcpip using Sock_streama
Af_inet represents IPV4.

Af_inet6 says IPV6
Af_unix,af_local indicates local communication
Sock_stream: Provides a stable connection-oriented data transfer, the TCP protocol.
OOB: You must use Connect () to establish the connection state before all data is transferred.
SOCK_DGRAM: Use a non-contiguous, unreliable packet connection.
Sock_seqpacket: Provides continuous and reliable packet connections.
Sock_raw: Provides access to the original network protocol.
SOCK_RDM: provides reliable packet connectivity.
Sock_packet: Communicates directly with the network driver.

The SendTo function sends a message through the socket interface, where a disconnected socket is used: the destination address of the message is specified by the addr. Details of the parameters are no longer explained.

The sprintf function writes formatted data to a string that returns the value: String length (strlen) For example:

char* who = "I";
char* whom = "csdn";
sprintf (S, "%s love%s.", who, whom); Produce: "I love Csdn." "This string is written to S.



receiving end: Receiver


RECEIVER.C:
#include "stdio.h" can only be used "" to indicate that,< is not displayed.

#include "Stdlib.h"
#include "string.h"
#include "Sys/socket.h"
#include "Netinet/in.h"
#include "Arpa/inet.h"
#include "Netdb.h"
int port=6789;
void Main ()
{
int Sin_len;
Char message[256];
int socket_descriptor;
struct sockaddr_in sin;
printf ("Waiting for data from sender\n");

Bzero (&sin,sizeof (sin));
Sin.sin_family=af_inet;
Sin.sin_addr.s_addr=htonl (inaddr_any);//htonl(the 32-bit host character sequence

                                                                                      // Convert to network character order)
            sin.sin_port=htons (port);//htons (converts 16-bit host character order to network character

                                                           //  order)
            sin_len=sizeof (SIN);
 
           socket_descriptor=socket (AF_ inet,sock_dgram,0);//Establish a Port
           bind (socket_ Descriptor, (struct sockaddr *) &sin,sizeof (sin));//host address

Binding with ports
while (1)
{
Recvfrom (socket_descriptor,message,sizeof (message), 0,
(struct sockaddr *) &sin,&sin_len);//Receive Message
printf ("Response from server:%s\n", message);
if (STRNMCP (message, "Stop", 4) ==0)//Compare Accept message and stop first 4

Character. > returns greater than 1,= returns 0.

{
printf ("Sender has told me end connection\n");
Break
}
}
Close (Socket_descriptor);
Exit (0);
}
respectively: Gcc-o xxx xxx.c Note: o is lowercase, uppercase words will prompt no xxx files or folders.
They are then run on separate tables:./xxx
Shown below:


Linux Learning four: UDP programming (top)

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.