① what is a socket.
The socket is the endpoint of a communication. A pair of processes communicate directly through a pair of sockets on the network, one for each process. A socket is determined by an IP address and port number. The socket encapsulates some operations that make data communication more convenient for two of processes in the network. Socket based on TCP protocol and UDP protocol is used a lot.
The following illustration shows the communication process in two ways
② several functions used to establish a socket for communication
Take the Linux system as an example to illustrate several functions
A Socket () function
int socket (int domain, int type, int protocol);
This action is similar to opening a file operation and returning the socket descriptor for the socket.
Parameters:
Domain: protocol domain, also known as the Protocol Family (family). The common protocol families are af_inet, Af_inet6, Af_local, Af_route. The Protocol family determines the address type of the socket, uses its corresponding address when communicating, af_inet with a combination of IPv4 address (32-bit) and 16-bit port number
Type: Specifies the socket type, which is commonly used for sock_stream, Sock_dgram, Sock_raw, Sock_packet, Sock_seqpacket, and the first two sockets corresponding to the TCP and UDP types respectively
Protocol: Specifies protocols that are commonly used for ipproto_tcp, IPPTOTO_UDP, IPPROTO_SCTP, IPPROTO_TIPC, and the types of protocols and sockets to match. 0 selects the default type for the type.
B Bind () function
int bind (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);
Assigning a specific address family address to a socket instead of being randomly allocated by the system.
Parameters:
Sockfd:socket descriptor, the int value returned by the socket () function
Addr: A const pointer to an address structure that points to the address to be bound to the SOCKFD, and the structure of the structure matches the address protocol.
corresponding to the IPv4.
struct SOCKADDR_IN {
sa_family_t sin_family;/* Address family: af_inet * * in_port_t sin_port ; /* Network byte-order port number *
/struct in_addr sin_addr; /*internet address *
/};
/* Internet address. * *
struct IN_ADDR {
uint32_t s_addr; /* Network byte-order address
/};
It should be noted that the Htol,htos function is used to convert host byte order to network byte order to avoid potential errors.
C Listen (), connect () function
When used, call the socket (), connect (), then call Listen () to listen to the socket, the client calls connect is, the server will receive this request.
int listen (int sockfd, int backlog);
SOCKFD is the descriptor of the socket to be tapped
Backlog is the maximum number of links that this socket can queue, which is the length of the socket's wait queue. Call Listen,socket to start waiting for a customer's link request
int Connect (int sockfd, const structsockaddr *addr, socklen_t Addrlen);
SOCKFD is the client socket descriptor
Addr is the socket address for the server
Addr_len is the length of the socket address.
The client establishes a connection to the TCP server by calling the Connect function. Call Listen () and the socket starts waiting for the customer's link request
D Accept () function
Server-side fourth to call the function, the server received the request, with accept accept the request, and then the link is established, you can start reading and writing operations.
int accept (int sockfd, struct sockaddr *addr, socklen_t *addrlen);
SOCKFD is the server socket descriptor
Addr is a pointer to return to the client address
Addrlen is the length of the protocol address. The return value of the function is a completely new descriptor that the kernel automatically generates, representing a TCP link to the client.
E.read (), write () read-write operation
The correlation function prototype is shown below
#include <unistd.h>
ssize_t Read (int fd, void *buf, size_t count);
ssize_t Write (int fd, const void *buf, size_t count);
#include <sys/types.h>
#include <sys/socket.h>
ssize_t Send (int sockfd, const void *buf, size_t len , int flags);
ssize_t recv (int sockfd, void *buf, size_t len, int flags);
ssize_t sendto (int sockfd, const void *buf, size_t len, int flags,
const struct SOCKADDR*DEST_ADDR, socklen_t Addrlen) ;
ssize_t recvfrom (int sockfd, void *buf, size_t len, int flags,
struct SOCKADDR*SRC_ADDR, socklen_t *addrlen);
ssize_t sendmsg (int sockfd, const struct MSGHDR *msg, int flags);
ssize_t recvmsg (int sockfd, struct msghdr*msg, int flags);
E. Close () function
To close the socket descriptor after reading and writing
#include <unistd.h>
int close (int fd);
③ code Example
Code originated from http://www.embedu.org/column/column179.htm
TCP sockets
TCP Service Side
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> # Include <stdlib.h> #include <string.h> #include <unistd.h> #include <netinet/in.h> #include <errno.h> #define MAX_MSG_SIZE 256 #define server_port 9987 #define BACKLOG 2 int getserveraddr (char * a
Ddrname) { printf ("Please input server addr:");
scanf ("%s", addrname); return 1; } int main () { int sock_fd,client_fd;/*SOCK_FD: Listening Socket;client_f D: Data transmission socket */ struct sockaddr_in ser_addr; /* Native address information */ struct sockaddr_in cli_addr; /* Client address information */ Char msg[max_msg_size];/* buffer */ int Ser_sockfd=socket (A f_inet,sock_stream,0)/* Create a connected socket */ if (ser_sockfd<0) {/* creation failed */  
fprintf (stderr, "Socker error:%s\n", Strerror (errno)); exit (1); }&N bsp; /* Initialize server address */ socklen_t addrlen=sizeof (struct sockaddr_in); nbsp; 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); } &NB Sp /* Listening client request */ 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 request */ int 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_ SOCKFD, MSG, (size_t) max_msg_size, 0); /* Accept Data */ printf ("received a connection from%SN", Inet_ntoa (Cli_add R.SIN_ADDR); printf ("%s\n", msg);/* print out on screen */ strcpy (msg, "Hi,i am server!"); Send (CLI_SOCKFD, MSG, sizeof (msg), 0); /* Send data */ Close (CLI_SOCKFD); &NBSP ; } } Close (SER_SOCKFD); return 0; &
nbsp
}
TCP Client
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/
inet.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netinet/in.h> #include <errno.h> #define MAX_MSG_SIZE 256 #define server_port 9987 int getserveraddr (char * addrname) {&N bsp; printf ("Please input server addr:"); scanf ("%s", Addrname); return 1; } int main () { int cli_sockfd;/* client Socke T */ int addrlen; Char seraddr[14]; struct S ockaddr_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 connectionSocket */ if (cli_sockfd<0) {/* Create failure */ F
printf (stderr, "Socker error:%s\n", Strerror (errno)); exit (1); } /* Initialize client address */ addrlen=sizeof (struct sockaddr_in); nbsp; 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) { * Bind failed */ fprintf (stderr, "bind error:%s\n", Strerror (errno)) ; exit (1); } /* Initialize server address */&nbs p; addrlen=sizeof (struct sockaddr_in); &nBsp
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 failure */ fprintf (s Tderr, "Connect error:%s\n", Strerror (errno); Close (CLI_SOCKFD); & nbsp exit (1); } strcpy (msg, "Hi,i am client!"); Send (CLI_SOCKFD, MSG, sizeof (msg), 0);/* Send data */ recv (CLI_SOCKFD, MSG , max_msg_size,0); * * Accept Data */ printf ("%s\n", msg);//print out on screen */ Close (CLI_SOCKFD); RetuRN 0; }
UDP Socket
UDP Service Side
int main () {int ser_sockfd;
int Len;
int Addrlen;
Socklen_t Addrlen;
Char seraddr[100];
struct sockaddr_in ser_addr;
/* Establish 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);
/* Display client-side network address/printf ("Receive from%s\n", Inet_ntoa (SER_ADDR.SIN_ADDR));
/* Display the client sent the string/printf ("recevce:%s", seraddr);
/* Return the string to the client side * * SendTo (ser_sockfd,seraddr,len,0, (struct sockaddr*) &ser_addr,addrlen);
return 0;
}
UDP client
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);
/* Establish socket*/cli_sockfd=socket (af_inet,sock_dgram,0);
if (cli_sockfd<0) {printf ("I cannot socket success\n");
return 1;
/* Fill out 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/len=read (stdin_fileno,buffer,sizeof (buffer) from standard input device);
/* Send string to server Side/sendto (cli_sockfd,buffer,len,0, struct sockaddr*) &cli_addr,addrlen); /* Receive 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);
return 0;
}
Description: This article is published by Giantpoplar in CSDN
Article Address http://blog.csdn.net/giantpoplar/article/details/47657303
Reprint please keep this note