Introduction to Socket-based UDP and TCP Programming

Source: Internet
Author: User

Reprinted from: http://www.dzsc.com/data/html/2009-12-22/81035.html

Author:Wang Shanshan, a lecturer at Huaqing vision embedded College.

I. Overview

TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are two different communication protocols at the transport layer in the network architecture TCP/IP model.

TCP: Transmission Control Protocol, a connection-oriented protocol that provides a reliable full-duplex byte STream for user processes. The TCP set interface is a byte STream socket interface).

UDP: User Datagram Protocol. UDP is a connectionless protocol. A udp interface is a type of data PACKET Socket.

II. Introduction to TCP and UDP

1) Basic TCP client-server programming framework

 

Note: (three-way handshake)

1. The client sends a SYN segment (synchronization serial number) to indicate the server port to be connected by the customer and the initialization serial number (ISN ).

2. the server sends back the SYN packet segment containing the server's initial serial number as the response. At the same time, set the check serial number (ACK) to the customer's ISN plus 1 to confirm the customer's SYN packet segment. A syn occupies a sequence number.

3. The customer must set the validation serial number to ISN plus 1 of the server to confirm the SYN packet segment of the server.

2) Basic TCP client-server programming framework Flowchart

 

3) Comparison of UDP and TCP:

From the above flowchart, we can see that UDP does not have a three-way handshake process.

To put it simply. UDP processing has fewer details than TCP. UDP cannot ensure that the message is sent to (It also reports that the message is not sent to) the destination. UDP does not guarantee the Transmission sequence of data packets. After UDP sends data, it can only be expected to reach the destination.

TCP advantages and disadvantages:

Advantages:

1. TCP explicitly creates and terminates connections in an agreed manner.

2. TCP ensures reliable, ordered (packets are received in the sent order), and non-repeated data transmission.

3. TCP processing flow control.

4. Data priority is allowed.

5. If the data is not transmitted, the TCP interface returns an error condition.

6. TCP maintains continuity and divides data blocks into smaller shards to handle big data blocks. -No need for programmers to know

Disadvantage: TCP must create (and maintain) a connection when transferring data. This connection adds overhead to the communication process, making it slower than UDP.

Advantages and disadvantages of UDP:

1. UDP does not require a connection

2. UDP does not incur any overhead because the receiver accepts the receipt of the packet (or automatically retransmits the packet when the packet does not arrive correctly.

3. UDP is designed for short applications and message control.

4. When a data packet is connected to a data packet, UDP requires less network bandwidth than TDP.

Iii. SOCKET programming

A Socket interface is an API of a TCP/IP network. A Socket interface defines many functions or routines that can be used by programmers to develop applications on a TCP/IP network. To learn TCP/IP network programming on the Internet, you must understand the Socket interface.

The Socket interface designer first places the interface in the Unix operating system. If you understand the input and output of Unix systems, you can easily understand Socket. Network Socket data transmission is a special type of I/O, and Socket is also a file descriptor. Socket also has a function called Socket () similar to opening a file. This function returns an integer Socket descriptor, and subsequent connection establishment and data transmission operations are implemented through this Socket. There are two common Socket types: stream Socket (SOCK_STREAM) and datagram Socket (SOCK_DGRAM ). Streaming is a connection-oriented Socket for connection-oriented TCP Service applications; datagram Socket is a connectionless Socket that corresponds to connectionless UDP Service applications.

1. socket call library functions mainly include:

Create socket

Socket (af, type, protocol)

Establish connection between address and Socket

Bind (sockid, local addr, addrlen)

The server listens to client requests.

Listen (Sockid, quenlen)

Establish connections between servers and clients (for TCP connections)

Client request connection

CONnect (sockid, destaddr, addrlen)

The server waits for receiving client connection requests from the Socket numbered Sockid.

Newsockid = accept (Sockid, Clientaddr, paddrlen)

Send/receive data

Connection orientation: send (sockid, buff, bufflen)

Recv ()

For connectionless connections: sendto (sockid, buff ,..., Addrlen)

Recvfrom ()

Release socket

Close (sockid)

2. TCP/IP application programming interface (API)

Workflow of the server: First call the socket function to create a Socket, then call the bind function to bind it to the local address and a local port number, and then call listen on the corresponding socket *, when accpet receives a connection service request, a new socket is generated. The SERver displays the IP address of the client and sends the string "hi, I am SERver!" to the client through the new socket! ". Close the socket.

Main ()
{
Int sock_fd, client_fd;/* sock_fd: * socket; client_fd: Data Transmission socket */
Struct sockaddr_in ser_addr;/* local address information */
Struct sockaddr_in cli_addr;/* client address information */
Char msg [MAX_MSG_SIZE];/* buffer */
Ser_sockfd =Socket(AF_INET, SOCK_STREAM, 0);/* Create the connected SOCKET */
If (ser_sockfd <0)
{/* Creation failed */
Fprintf (stderr, "socker Error: % s \ n", strerror (errno ));
Exit (1 );
}
/* Initialize the server address */
Addrlen = sizeof (struct sockaddr_in );
Bzero (& ser_addr, addrlen );
Ser_addr.sin_family = AF_INET;
Ser_addr.sin_addr.s_addr = htonl (INADDR_ANY );
Ser_addr.sin_port = htons (SERVER_PORT );
If (Bind(Ser_sockfd, (struct sockaddr *) & ser_addr, sizeof (struct sockaddr_in) <0)
{/* Binding failed */
Fprintf (stderr, "Bind Error: % s \ n", strerror (errno ));
Exit (1 );
}
/* Listen for client requests */
If (Listen(Ser_sockfd, BACKLOG) <0)
{
Fprintf (stderr, "Listen Error: % s \ n", strerror (errno ));
Close (ser_sockfd );
Exit (1 );
}
While (1)
{/* Waiting for receiving client connection requests */
Cli_sockfd =Accept(Ser_sockfd, (struct sockaddr *) & cli_addr, & addrlen );
If (cli_sockfd <= 0)
{
Fprintf (stderr, "Accept Error: % s \ n", strerror (errno ));
}
Else
{/* Start Service */
Recv(Cli_addr, msg, MAX_MSG_SIZE, 0);/* accept data */
Printf ("received a connection from % sn", inet_ntoa (cli_addr.sin_addr ));
Printf ("% s \ n", msg);/* print it out on the screen */
Strcpy (msg, "hi, I am server! ");
Send(Cli_addr, msg, sizeof (msg), 0);/* sent data */
Close (cli_addr );
}
}
Close(Ser_sockfd );
}

Client workflow: First call the socket function to create a Socket, then call the bind function to bind it to the local address and a local port number, and request to connect to the server, send the string "hi, I am client!" to the client through the new socket! ". Close the socket.

Main ()
{
Int cli_sockfd;/* client SOCKET */
Int addrlen;
Char seraddr [14];
Struct sockaddr_in ser_addr,/* server address */
Cli_addr;/* client address */
Char msg [MAX_MSG_SIZE];/* buffer */
GetServerAddr (seraddr );
Cli_sockfd =Socket(AF_INET, SOCK_STREAM, 0);/* Create the connected SOCKET */
If (ser_sockfd <0)
{/* Creation failed */
Fprintf (stderr, "socker Error: % s \ n", strerror (errno ));
Exit (1 );
}
/* Initialize the client address */
Addrlen = sizeof (struct sockaddr_in );
Bzero (& ser_addr, addrlen );
Cli_addr.sin_family = AF_INET;
Cli_addr.sin_addr.s_addr = htonl (INADDR_ANY );
Cli_addr.sin_port = 0;
If (Bind(Cli_sockfd, (struct sockaddr *) & cli_addr, addrlen) <0)
{
/* Fixed failure */
Fprintf (stderr, "Bind Error: % s \ n", strerror (errno ));
Exit (1 );
}
/* Initialize the server address */
Addrlen = sizeof (struct sockaddr_in );
Bzero (& ser_addr, addrlen );
Ser_addr.sin_family = AF_INET;
Ser_addr.sin_addr.s_addr = inet_addr (seraddr );
Ser_addr.sin_port = htons (SERVER_PORT );
If (Connect(Cli_sockfd, (struct sockaddr *) & ser_addr, & addrlen )! = 0)/* request connection */
{
/* Connection Failed */
Fprintf (stderr, "Connect Error: % s \ n", strerror (errno ));
Close(Cli_sockfd );
Exit (1 );
}
Strcpy (msg, "hi, I am client! ");
Send (sockfd, msg, sizeof (msg), 0);/* send data */
Recv (sockfd, msg, MAX_MSG_SIZE, 0);/* accept data */
Printf ("% s \ n", msg);/* print it out on the screen */
Close(Cli_sockfd );
}

3. UDP/IP Application Programming Interface (API)

Server workflow: First call the socket function to create a Socket, and then call the bind function to bind it to the local address and a local port number. When receiving a client, the server displays the IP address of the client and returns the string to the client.

Int main (int argc, char ** argv)
{
Int ser_sockfd;
Int len;
// Int addrlen;
Socklen_t addrlen;
Char seraddr [100];
Struct sockaddr_in ser_addr;
/* Create a socket */
Ser_sockfd = socket (AF_INET, SOCK_DGRAM, 0 );
If (ser_sockfd <0)
{
Printf ("I cannot socket success \ n ");
Return 1;
}
/* Fill in the sockaddr_in structure */
Addrlen = sizeof (struct sockaddr_in );
Bzero (& ser_addr, addrlen );
Ser_addr.sin_family = AF_INET;
Ser_addr.sin_addr.s_addr = htonl (INADDR_ANY );
Ser_addr.sin_port = htons (SERVER_PORT );
/* Bind the client
If (bind (ser_sockfd, (struct sockaddr *) & ser_addr, addrlen) <0)
{
Printf ("connect ");
Return 1;
}
While (1)
{
Bzero (seraddr, sizeof (seraddr ));
Len = recvfrom (ser_sockfd, seraddr, sizeof (seraddr), 0, (struct sockaddr *) & ser_addr, & addrlen );
/* Display the network address of the client */
Printf ("receive from % s \ n", inet_ntoa (ser_addr.sin_addr ));
/* Display the string sent from the client */
Printf ("recevce: % s", seraddr );
/* Return the string to the client */
Sendto (ser_sockfd, seraddr, len, 0, (struct sockaddr *) & ser_addr, addrlen );
}
}

Client workflow: first, call the socket function to create a Socket, enter the server address and port number, obtain the string from the standard input device, and send the string to the server, and receives the string returned by the server. Close the socket.

Int GetServerAddr (char * addrname)
{
Printf ("please input server addr :");
Scanf ("% s", addrname );
Return 1;
}
Int main (int argc, char ** argv)
{
Int cli_sockfd;
Int len;
Socklen_t addrlen;
Char seraddr [14];
Struct sockaddr_in cli_addr;
Char buffer [256];
GetServerAddr (seraddr );
/* Create a socket */
Cli_sockfd = socket (AF_INET, SOCK_DGRAM, 0 );
If (cli_sockfd <0)
{
Printf ("I cannot socket success \ n ");
Return 1;
}
/* Fill in sockaddr_in */
Addrlen = sizeof (struct sockaddr_in );
Bzero (& cli_addr, addrlen );
Cli_addr.sin_family = AF_INET;
Cli_addr.sin_addr.s_addr = inet_addr (seraddr );
// Cli_addr.sin_addr.s_addr = htonl (INADDR_ANY );
Cli_addr.sin_port = htons (SERVER_PORT );

Bzero (buffer, sizeof (buffer ));
/* Obtain the string from the standard input device */
Len = read (STDIN_FILENO, buffer, sizeof (buffer ));
/* Send the string to the server */
Sendto (cli_sockfd, buffer, len, 0, (struct sockaddr *) & cli_addr, addrlen );
/* Receives the string returned by the server */
Len = recvfrom (cli_sockfd, buffer, sizeof (buffer), 0, (struct sockaddr *) & cli_addr, & addrlen );
// Printf ("receive from % s \ n", inet_ntoa (cli_addr.sin_addr ));
Printf ("receive: % s", buffer );
Close (cli_sockfd );
}

Iv. debugging

Makefile:

CC = gcc
All: server client
CFLAGS =-o
Server: server. c
$ (CC) $ (CFLAGS) $ @ server. c
Client: client. c
$ (CC) $ (CFLAGS) $ @ client. c

Clean:
Rm-f server client

Execute make in shell to compile and make clean to delete the generated file.

The running result is as follows:


"This article is written by Hua Qing vision http://www.embedu.org/index.htm"

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.