Linux system socket Communication Programming 2

Source: Internet
Author: User
Tags server port htons

I. OverviewTCP (Transmission Control Protocol) and UDP (User Datagram Protocol are two different communication protocols in the network architecture TCP/IP model in the layer of transport layer. TCP: Transmission Control Protocol, a connection-oriented protocol that provides a reliable full-duplex byte stream for user processes, and a TCP socket interface is a type of byte-throttle socket Interface (stream socket). UDP: User Datagram Protocol. UDP is a non-connectivity protocol. The UDP socket interface is one of the datagram socket interfaces (datagram sockets). Ii. introduction of TCP and UDP1) Basic TCP client-server programming framework

Description: (Three-way handshake)
1. The client sends a SYN segment (synchronous sequence number) that indicates the server port to which the customer intends to connect, and the initialization sequence number (ISN).
2. The server sends back the SYN message segment that contains the initial sequence number of the server as a reply. At the same time, the confirmation sequence number (ACK) is set to customer's ISN plus 1 to confirm the customer's SYN message segment. A SYN will occupy an ordinal number.
3. The customer must set the confirmation number to the server's ISN plus 1 to confirm the SYN message segment of the server.

2) Basic TCP client-server programming basic framework Flowchart

3) Comparison of UDP and TCP:from the above flowchart we can clearly see that UDP does not have three handshake process. simply put. UDP handles less detail than TCP. UDP does not guarantee that a message is delivered to (it also reports that the message is not delivered to) the destination. UDP also does not guarantee the order in which packets are sent. UDP sends out the data only to expect it to reach its destination. TCP pros and Cons:Advantages:
1. TCP provides an acceptable way to explicitly create and terminate a connection.
2. TCP guarantees reliable, sequential (packets received in the order in which they are sent) and data transfers that are not duplicated.
3. TCP processing Flow control.
4. Allow data to take precedence
5. If the data is not delivered to, then the TCP socket interface returns an error status condition.
6. TCP handles large chunks of data by maintaining continuous and dividing chunks into smaller shards. -No need for programmers to knowdisadvantage: TCP must create (and maintain) a connection when transferring data. This connection adds overhead to the communication process, making it slower than the UDP speed. UDP pros and Cons:
1. UDP does not require a connection to be maintained
2. UDP does not have the overhead of receiving a packet (or automatically retransmission when the packet does not arrive correctly) due to the recipient's approval.
3. UDP is designed to be used for short applications and control messages
4. UDP requires less network bandwidth than TDP on the basis of a packet connected to a packet. third, socket programmingThe socket interface is a TCP/IP network Api,socket interface that defines many functions or routines that programmers can use to develop applications on TCP/IP networks. To learn TCP/IP network programming on the Internet, you must understand the socket interface. The Socket interface Designer is the first to put the interface in the UNIX operating system. If you understand the input and output of UNIX systems, it is easy to understand the socket. The network socket data transmission is a special i/o,socket is also a kind of file descriptor. The socket also has a function call socket () that resembles an open file, which returns an integer socket descriptor, followed by connection creation, data transfer, and so on, through the socket. There are two common types of sockets: Streaming Sockets (SOCK_STREAM) and datagram Sockets (SOCK_DGRAM). Streaming is a connection-oriented socket for connection-oriented TCP service applications; A datagram socket is a non-connected socket that corresponds to a non-connected UDP service application. 1, the socket call library functions are mainly:Creating sockets
Socket (Af,type,protocol)establish contact for addresses and sockets
Bind (sockid, local addr, Addrlen)Server-side listening for client requests
Listen (Sockid, Quenlen)establishing a server/client connection (connection-oriented TCP)
Client Request Connection
Connect (Sockid, destaddr, Addrlen)
Server side waits for client connection requests to be received from a socket numbered Sockid
Newsockid=accept (sockid,clientaddr, Paddrlen)Send/Receive data
Connection oriented: Send (Sockid, buff, Bufflen)
Recv ()
For no connection: sendto (sockid,buff,..., Addrlen)
Recvfrom ()Release Socket
Close (Sockid)2. TCP/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 native address and a local port number, and then call listen to listen on the corresponding socket, when Accpet receives a connection service request, A new socket will be generated. The server displays the IP address of the client and sends the string "Hi,i am server!" to the client through a new socket. Finally, close the socket.

Main ()
{
int sock_fd,client_fd; /*SOCK_FD: Monitor SOCKET;CLIENT_FD: Data transfer Socket */
struct sockaddr_in ser_addr; /* Native 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 a connected socket */
if (ser_sockfd<0)
{/* Create 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)
{/* bind 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 to receive 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 out on the screen */
strcpy (msg, "Hi,i am server!");
Send (Cli_addr,msg,sizeof (msg), 0); /* Data sent */
Close (CLI_ADDR);
}
}
Close (SER_SOCKFD);
}

Client Workflow: First call the socket function to create a socket and then call the BIND function to bind it to the native address and a local port number, request a connection to the server, and send the string "Hi,i am client!" to the client via a new socket. Finally, close the socket.

Main ()
{
int cli_sockfd;/* Client Socket */
int Addrlen;
Char seraddr[14];
struct sockaddr_in address of the ser_addr,/* server */
Address of the cli_addr;/* client */
Char msg[max_msg_size];/* buffer */
GETSERVERADDR (SERADDR);
Cli_sockfd=socket (af_inet,sock_stream,0);/* Create a connected socket */
if (ser_sockfd<0)
{/* Create 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)
{
/* Failure of the bar */
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)/*/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);/* Sends data */
Recv (sockfd,msg,max_msg_size,0); /* Accept Data */
printf ("%s\n", msg);/* print 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 native address and a local port number, when a client is received, 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;
/* Build 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 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);
/* Displays the network address of the client side */
printf ("Receive from%s\n", Inet_ntoa (SER_ADDR.SIN_ADDR));
/* Displays the string sent by the client */
printf ("recevce:%s", seraddr);
/* Return the string to client side */
SendTo (ser_sockfd,seraddr,len,0, (struct sockaddr*) &ser_addr,addrlen);
}

Client Workflow: First call the socket function to create a socket, fill in the server address and port number, get the string from the standard input device, pass the string to the server side, and receive the string returned by the server side. Finally, 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);
/* Build 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));
/* Get string from standard input device */
Len=read (stdin_fileno,buffer,sizeof (buffer));
/* Send string to server side */
SendTo (cli_sockfd,buffer,len,0, (struct sockaddr*) &cli_addr,addrlen);
/* Receive the server-side returned string */
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);
}

Four, commissioningThe makefile file is:

CC=gcc
        all:server client
        CFLAGS=-o
        server: server.c
         $(CC) $(CFLAGS) [email protected] server.c
        client: client.c
        $(CC) $(CFLAGS) [email protected] client.c
clean:
        rm -f server client

execute make in the shell to compile, making clean to delete the build file. running results such as:

Linux system socket Communication Programming 2

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.