Simple socket communication instances in Linux and linuxsocket instances

Source: Internet
Author: User

Simple socket communication instances in Linux and linuxsocket instances

Simple socket communication instances in Linux

 

If you spend too much time thinking about a thing, you'll never get it done.

-Bruce Lee

I have been learning network programming for some time. When I first read "UNIX network programming", I think this thick book is hard! Later, I found that it was not as difficult as I thought. If you are a newbie, we recommend that you start handwriting code after the second part is complete. No code is required. I did not repeat it for 100 times to make it clear. After you have typed it, read the book with questions, and you will be more targeted. The speed of improvement is fast. This is the only way to learn any book or language.

I wrote this blog because I checked a lot of things written by others at the beginning. After Baidu, I found that everyone only posted all the code. The functions of each function are not described. I don't even know which function is under which header file. I am not familiar with functions. Next, I will write down the functions of each function, its header files, and function prototype. For your reference, I hope you can correct what is wrong when I write my blog for the first time. You can leave a message below, which is also the motivation for me to continue writing.

I hope to share with you all the difficulties and difficulties encountered in learning network programming. I also hope to discuss the problems and grow together. If you are planning to learn network programming at the beginning, this article will certainly help you.

My mailbox: cvmimi_linhai@foxmail.com, reprinted please indicate the source: http://www.cnblogs.com/yusenwu/p/4579167.html.

About how to introduce this simple instance:

--> 1. Code display and function Introduction

--> 2. First, introduce the functions of functions on the client and server and the prototype of functions.

--> 3. Group switching between three-way handshake and TCP connection Closure

--> 4. IPv4 and IPv6 socket address Structure

--> 5. Summary of some good learning Websites

--> 6. Download Code

Client. c

 1  #include <stdio.h> 2  #include <sys/socket.h> 3  #include <sys/types.h> 4  #include <stdlib.h> 5  #include <netinet/in.h> 6  #include <errno.h> 7  #include <string.h> 8  #include <arpa/inet.h> 9  #include <unistd.h>10  #define MAXLINE 102411  int main(int argc,char **argv)12  {13  char *servInetAddr = "127.0.0.1";14  int socketfd;15  struct sockaddr_in sockaddr;16  char recvline[MAXLINE], sendline[MAXLINE];17  int n;18  19  if(argc != 2)20  {21  printf("client <ipaddress> \n");22  exit(0);23  }24  25  socketfd = socket(AF_INET,SOCK_STREAM,0);26  memset(&sockaddr,0,sizeof(sockaddr));27  sockaddr.sin_family = AF_INET;28  sockaddr.sin_port = htons(10004);29  inet_pton(AF_INET,servInetAddr,&sockaddr.sin_addr)
30 if((connect(socketfd,(struct sockaddr*)&sockaddr,sizeof(sockaddr))) < 0 )
31 {31 printf("connect error %s errno: %d\n",strerror(errno),errno);32 exit(0);33 }34 35 printf("send message to server\n");36 37 fgets(sendline,1024,stdin);38 39 if((send(socketfd,sendline,strlen(sendline),0)) < 0)40 {41 printf("send mes error: %s errno : %d",strerror(errno),errno);42 exit(0);43 }44 45 close(socketfd);46 printf("exit\n");47 exit(0);48 }

-Execution: gcc client. c-o client is started./client is started before it starts./server -----------------------------------------

Server. c

 1  #include <stdio.h> 2  #include <sys/socket.h> 3  #include <sys/types.h> 4  #include <string.h> 5  #include <netinet/in.h> 6  #include <stdlib.h> 7  #include <errno.h> 8  #include <unistd.h> 9  #include <arpa/inet.h>10  11  #define MAXLINE 102412  int main(int argc,char **argv)13  {14  int listenfd,connfd;15  struct sockaddr_in sockaddr;16  char buff[MAXLINE];17  int n;18  19  memset(&sockaddr,0,sizeof(sockaddr));20  21  sockaddr.sin_family = AF_INET;22  sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);23  sockaddr.sin_port = htons(10004);24  25  listenfd = socket(AF_INET,SOCK_STREAM,0);26  27  bind(listenfd,(struct sockaddr *) &sockaddr,sizeof(sockaddr));28  29  listen(listenfd,1024);30 31  32  printf("Please wait for the client information\n");33  34  for(;;)35  {36  if((connfd = accept(listenfd,(struct sockaddr*)NULL,NULL))==-1)37  {38  printf("accpet socket error: %s errno :%d\n",strerror(errno),errno);39  continue;40  }41  42  n = recv(connfd,buff,MAXLINE,0);43  buff[n] = '\0';44  printf("recv msg from client:%s",buff);45  close(connfd);46  }47  close(listenfd);48  }

-Run gcc server. c-o server and then start the./server program -------------------------------------------------------

 

> 1. Code display and function Introduction

   The above simple socket communication code is to be implementedFunction: After a message is sent from the client, the server receives the message and displays it on the server (recv msg from client :****).

   

> 2. First, we will introduce the functions of functions on the client and server, as well as the prototype of functions. 

# Include <sys/socket. h> int socket (int family, int type, int protocol); // specify the expected communication protocol type. The returned file descriptor is similar to the socket descriptor. We become the socket descriptor, sockfd for short.

Family: protocol family

Family Description
AF_INET IPv4 protocol
AF_INET6 IPv6
AF_LOCAL Unix domain protocol (chapter 15)
AF_ROUTE Routing socket (chapter 18)
AF_KEY Key socket (Chapter 19)

Type: Socket type

Type Description
SOCK_STREAM (common) Byte stream socket
SOCK_DGRAM Datagram socket
SOCK_SEQPACKET Ordered grouping socket
SOCK_RAW Original socket

Protocol: a constant orSet to 0To select the default value of the combination of family and type.

Protocol Description
IPPROTO_TCP TCP transmission protocol
IPPROTO_UDP UDP transmission protocol
IPPROTO_SCTP SCTP transmission protocol

# Include <arpa/inet. h> int inet_ton (int family, const char * strptr, void * addrptr); // 1 is returned for success, 0 is returned for incorrect format, and-1 is returned for Error
// Function: p indicates that expression n indicates that this function may be required in all code written after a value, so this function is very important.
// Store the string pointed to by char through the addrptr pointer
// Its Inverse Function: inet_ntop () has the opposite effect. You can refer to Baidu for the functions of this function. We will not introduce it because it is not involved in this example. Later
// When an error occurs, the errno value is set to EAFNOSUPPORT.
# Include <sys/socket. h> int connect (int sockfd, const struct sockaddr * servaddr, socklen_t addrlen); // use the connect function to establish a connection with the TCP Server
# Include <unistd. h> int close (int sockfd); // close the socket and terminate the TCP Connection
# Include <sys/socket. h> int bind (int sockfd, const struct * myaddr, socklen_t addrlen); // assign the local Protocol address to a socket. That is, a combination of 32-bit IPv4 or 128-bit ipv6 and 16-bit TCP or UDP.
# Include <sys/socket. h> int listen (int sockfd, int backlog) // 0 is returned for success and-1 is returned for failure. The listen function is called only by the TCP server.
// The listen function will do two things:
// 1: We used the socket function when creating the socket. The socket it creates is an active socket. The function of the bind function is to convert the active socket into a passive socket through this function, tell the kernel to accept requests directed to this socket. The CLOSED status changes to the LISTEN status.
// 2: The second parameter of this function specifies the maximum number of connections that the kernel will queue for the socket.
# Include <sys/socket. h> int accept (int sockfd, struct sockaddr * cliaddr, socklen_t * addrlen); // a descriptor is returned for success, and-1 is returned for failure.
// 1. If the second three parameters are NULL, it indicates that we are not interested in the customer's identity and therefore set it to NULL;
// 2. The first parameter is the listening socket created by the socket. The returned result is a connected socket. The two sockets are different and important.Differences:The listener socket we created is generally created on only one server and always exists. The kernel will establish a connection socket for the Client Connection of each server process. When the server completes the service for a given customer, the connection socket will be closed.

> 3. Group switching between three-way handshake and TCP connection Closure

  Three-way handshake:

To better understand the connect, bind, and close functions, it is necessary to understand the establishment and termination of TCP connections. (Be sure to understand all the functions above and then read this section again ).

1. The server must be opened first, waiting for external connections to be accepted. The preceding example uses the socket, bind, and listen functions. The server is calledPassive open.

2. The client is initiated through connect.Open it.

3. After opening the node, the client TCP sends a SYN (synchronous) Sub-section, which tells the server that the client will be connectedThe initial serial number of the sent data only,The SYN node does not carry data. It sends an IP datagram with only one IP header, one TCP header, and TCP options.

4. The server must confirm (ACK) the customer's SYN and also send a SYN Shard, which contains the initial serial number of the data that the server will send in the same connection. The server sends SYN and ACK acknowledgment (+ 1) to customer SYN in a single shard ).

5. The customer must confirm the SYN segmentation of the server.

The above process is called the three-way handshake of TCP.

Note: SYN (synchronous) is the handshake signal used when TCP/IP establishes a connection. When a normal TCP network connection is established between the client and the server, the client first sends a SYN message. The server uses the SYN + ACK response to receive the message, and the client then responds with the ACK message. In this way, a reliable TCP connection can be established between the client and the server, and data can be transmitted between the client and the server.

 

  TCP connection termination

  To terminate a connection, there are four sub-sections.

1. By calling close, we executeActive Shutdown, TCP sendsFIN(Finish) indicates that the data has been sent.

2. After receiving the FIN, the peer executesDisable it passively.

3. After a while, the application process that receives the file Terminator will call close to close its socket. Therefore, the socket also sends a FIN.

4. confirm that this fin ack + 1 is clearly expressed.

5. We also call it TCP four handshakes.

1 struct in_addr {2 in_addr_t s_addr; 3}; 4 5 struct sockaddr_in {6 uint8_t sin_len; // unsigned 8-bit integer 7 sa_family_t sin_famliy;/* AF_INET */8 in_port_t sin_port;
9 struct in_addr sin_addr;/* 32-bit IPv4 address */10 char sin_zero [8];/* unuse */11 };
// Header file # include <sys/types. h>
// Sa_family_t and socklen_t header files # include <sys/socket. h>
// In_addr_t in_port_t header file # include <netinet/in. h>

 

IPv6 address structure:

struct in6_addr {   uint8_t  s6_addr[16];  };#define SIN6_LENstruct sockaddr_in6 {   uint8_t sin6_len;   sa_family_t sin6_famliy;   in_port_t  sin6_port;   uint32_t sin6_flowinfo;   struct in6_addr sin6_addr;   uint32_t sin6_scope_id;   };

 

> 5. Summary of some good learning Websites

  1. Video seek on 51CTO. It is not as good as a teacher to read books. A waste of money.

2. http://www.cnblogs.com/skynet/archive/2010/12/12/1903949.html

Http://blog.csdn.net/hguisu/article/details/7445768/

Http://www.oschina.net/code/snippet_97047_675

These blogs are good and can help you get started.

> 6. Download Code

> 7. Summary

   The road to learning is quite long. It is very difficult to learn well and requires long-term accumulation. I am also learning. After a lot of setbacks, but with an ideal, you will be able to succeed. I hope you will come to the Linux Server programming team.

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.