Preface : Organize the Linux socket programming related APIs and knowledge points
Flow Socket Processing Flow
Datagram Socket processing Flow
byte order : Byte order has a small end of the big-endian, different processing architectures when storing a multibyte number, if the low memory address stores the high part of the number, it is called the big endian byte order, or vice versa is called the small end byte order. Therefore, in order to unify the byte order of the data transmitted in the network, there is the network order, and the data sent to the network must adopt the network order.
function of host byte order to network byte order
#include <arpa/inet.h>
uint32_t htonl (uint32_t t)//h represents the host hostname byte order, n represents the net network byte order, L represents the long type, s represents the short type//converts host byte order to network byte order
uint16_t htons (uint16_t t)
uint32_t Ntohl (uint32_t t)//Turn network byte order to host byte order
uint16_t Ntohs (uint16_t t)
Address format: An abstraction of the address of the connection host
struct sockaddr{
unsigned short sa_family; Address protocol family, generally af_inet, representing the IPV4 protocol
Char sa_data[14];
};
This structure is not good, so there is another structure
struct sockaddr_in{
short int sin_family; Address protocol family, generally af_inet, representing the IPV4 protocol
unsigned short int sin_port; Port number, 0 for random selection
struct IN_ADDR sin_addr; IP address inaddr_any means using its own IP address
unsigned char sin_zero[8]; Tim 0, to be as big as sockaddr.
};
struct in_addr{
unsigned long s_addr;
};
IP Address Translation:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
in_addr_t inet_addr (const char *CP); The IP address string is converted to the appropriate type, the network sequence is converted, and the error returns-1, which is 255.255.255.255
char * Inet_nota (struct in_addr);//Convert IP address to string
Socket type: Sock_stream streaming sockets use the TCP protocol, a reliable, connection-oriented byte-stream service. Sock_dgram datagram sockets for non-connected, unreliable datagram services. There is also an original socket for protocol development, compared to the underlying.
Socket function
#include <sys/types.h>
#include <sys/socket.h>
int socket (int domain,int type,int protocol); Domain protocol family, type socket types, protocol typically 0, return a socket descriptor, equivalent to a file descriptor error return-1
Bind function: Binds the socket descriptor to the address
#include <sys/types.h>
#include <sys/socket.h>
int bind (int sockfd,struct sockaddr *my_addr,int addrlen); SOCKFD socket descriptor, Addrlen for sizeof (struct sockaddr)
Connect function
#include <sys/types.h>
#include <sys/socket.h>
int connect (int sockfd,struct sockaddr *serv_addr,int addrlen);
Listen function
#include <sys/types.h>
#include <sys/socket.h>
int listen (int sockfd,int backlog); Backlog represents the maximum number of non-processed connection request queues that can be accommodated, typically set to a number between 5-10
Accept function
#include <sys/socket.h>
int accept (int sockfd,void *addr,int *addrlen),//SOCKFD is a socket descriptor listen, addr pointer to struct SOCKADDR type, used to store the address of the remote connection endpoint. Addrlen the length of the address, which returns the socket descriptor for the remote endpoint address.
A function that accepts a message and sends a message
#include <sys/types.h>
#include <sys/socket.h>
int send (int sockfd,const void *msg,int len,int flags); SOCKFD a socket descriptor for a remote connection, MSG points to a pointer to a message struct, the number of bytes of the Len message, and flags is typically 0, returning the length of the data being sent. The Send function has a size limit and can be sent multiple times if there is too much data to send.
int recv (int sockfd,void *buf,int len,unsigned flags);//Returns the length of buf,
The above 2 functions are used for streaming sockets
int sendto (int sockfd,const void *msg,int len,unsigned int flags,const struct sockaddr *to,int tolen);
SOCKFD socket for remote host, SOCKADDR address of remote host
int recvfrom (int sockfd,void *buf,int len,unsigned int flags, struct sockaddr *from,int *fromlen);
These 2 functions are used with datagram sockets
Close and shutdown functions
Close (SOCKFD)//close socket, socket will not allow read and write operations
#include <sys/socket.h>
int shutdown (int sockfd,int how)//how:0 means that data is not allowed, 1, which means that data is not allowed, 2 and colse.
Tcpserver.c
#include <stdio.h>#include<stdlib.h>#include<string.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/inch.h>#include<unistd.h>#include<sys/wait.h>#definePORT 4008#defineBACKLOG 10#defineBUFSIZE 4096voidProcessChar*cmd);intMainintargcChar*argv[]) { intLSOCKFD,RSOCKFD; structsockaddr_in Lsocket,rsocket; if(Lsockfd=socket (Af_inet,sock_stream,0)) <0)//server-side socket {perror ("Socket"); Exit (1); } lsocket.sin_family=af_inet; Set server-side address Lsocket.sin_port=htons (PORT); Lsocket.sin_addr.s_addr=Inaddr_any; Bzero (& (Lsocket.sin_zero),8); if(Bind (LSOCKFD, (structSOCKADDR *) &lsocket,sizeof(structSOCKADDR)) <0)//Bind the server-side address to socket binding {perror ("Bind"); Exit (1); } if(Listen (Lsockfd,backlog) <0)//Listen to the server-side socket and, if there is a client connect, add it to the listening queue {perror ("Listen"); Exit (1); } intSin_size=sizeof(structsockaddr); intCount=0; while(1) {printf ("Wait for connecting!\n"); if(Rsockfd=accept (LSOCKFD, (structSOCKADDR *) &rsocket,&sin_size) <0)//Processing client request {perror ("Accept"); Continue; } Count++; printf ("someone connect!,current people%d\n", Count); if(!Fork ())//For a client to establish a processing sub-process to send and receive data {CharStr[bufsize]; intnumbytes=0; while(1) { if((Numbytes=recv (rsockfd,str,bufsize-1,0)) <0) {perror ("recv"); Break; } Str[numbytes]=' /'; if(strcmp (str,"quit")==0) {printf ("Client quit!\n"); Break; } printf ("receive a message:%s\n", str); if(Send (Rsockfd,str,strlen (str),0) <0) {perror ("Send"); Break; }} close (RSOCKFD); Exit (0); } while(Waitpid (-1, Null,wnohang) >0)//This does not block if the third parameter is wuntraced, it will block if a client child process exits, then output the relevant statement{Count--; printf ("someone quit!,current people have%d\n", Count); } } return 0;}
tcpclient.c gcc tcpclient.c-o tcpclient run tcpclient 127.0.0.1//input quit quit
#include <stdio.h>#include<stdlib.h>#include<string.h>#include<netdb.h>#include<errno.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/inch.h>#include<arpa/inet.h>#definePORT 4008#defineMaxdatasize 4096#defineBUFSIZE 4096intMainintargcChar*argv[]) { intRSOCKFD; structsockaddr_in Rsocket; if(argc!=2) {fprintf (stderr,"usage:client hostname\n"); Exit (1); } if(Rsockfd=socket (Af_inet,sock_stream,0)) <0)//Create a server-side socket {perror ("sock"); Exit (1); } rsocket.sin_family=af_inet; Set server-side address Rsocket.sin_port=htons (PORT); Rsocket.sin_addr.s_addr=INET_ADDR (argv[1]); //if (Inet_pton (af_inet,argv[1],&rsocket.sin_addr) <0)// { //perror ("Inet_pton"); //exit (1); // } //rsocket.sin_addr=* (struct in_addr*) he->h_addr;Bzero (& (Rsocket.sin_zero),8); if(Connect (RSOCKFD,structsockaddr*) &rsocket,sizeof(structSOCKADDR)) <0)//connection server {perror ("Connect"); Exit (1); } CharSstr[bufsize]; CharRstr[bufsize]; while(1)//Send and receive data, enter quit {printf ("%15s","command is:"); intlen=0; Fgets (Sstr,bufsize,stdin); Sstr[strlen (SSTR)-1]=0; if(Send (Rsockfd,sstr,strlen (SSTR),0) <0) {perror ("Send"); Continue; } if(strcmp (SSTR,"quit")==0) Break; intnumbytes=0; if((Numbytes=recv (rsockfd,rstr,bufsize-1,0)) <0) {perror ("recv"); Continue; } Rstr[numbytes]=' /'; printf ("%15s%s\n","result is:", RSTR); } close (RSOCKFD); return 0;}
Linux Network programming