Directory
1. Socket overview
2. Address and Order Processing
3. Function Introduction
4. Usage examples
1. Socket Overview
1. The TCP protocol establishes the connection through the three-time handshake protocolThe TCP protocol completes the establishment of the connection through three message segments, which is called a three-time handshake (three-way handshake), as shown in the process.
First handshake: When a connection is established, the client sends a SYN packet (SYN=J) to the server and enters the Syn_send state, waiting for the server to confirm; SYN: Synchronous sequence Number (Synchronize Sequence Numbers).
Second handshake: The server receives the SYN packet, it must confirm the customer's SYN (ACK=J+1), and also send itself a SYN packet (syn=k), that is, the Syn+ack packet, when the server enters the SYN_RECV state;
Third handshake: The client receives the server's Syn+ack packet, sends the acknowledgment packet ack (ACK=K+1) to the server, the packet is sent, the client and the server enter the established state, and the handshake is completed three times.
A full three-time handshake is also: request---answer---confirm again.
The corresponding function interface:
As you can see, when the client calls connect, the connection request is triggered, the SYN J packet is sent to the server, then connect enters the blocking state, the server hears the connection request, receives the SYN J packet, calls the Accept function to receive the request to send SYN K to the client, ACK j+ 1, then accept into the blocking state, the client receives the server SYN K, after the ACK j+1, then connect returns, and the Syn K Confirmation, the server received an ACK k+1, accept return, this three times the handshake is completed, the connection is established.
2. Programming Process
2. Address and Order Processing
1. Address structure related processing
struct socketaddr{
unsigned short sa_family;
Char sa_data[14]
}
struct socketaddr_in{
Short int sa_family;//address family, even with what address, IPV4 or IPV6
unsigned short int sin_port;
struct IN_ADDR sin_addr;//Storage IP Address
unsigned char sin_zero[8]//padding 0 to keep also struct socketaddr same size
}
2, data storage priority order
Network address and host address translation
#include <netinet/in.h>
uint16_t htons (uint16_t host16bit)//host address to network address translation
uint32_t htols (uint32_t host32bit)
uint16_t Ntohs (uint16_t net16bit)//network address to host address translation
uint32_t Ntohl (uint32_t net32bit)
Success: Returns the byte order to convert
Error:-1
3. Address format Conversion
Converts the address of a decimal representation into a binary
#include <arpa/inet.h>
int Inet_pton (int family,//protocol type
const char *strptr,//the value to convert
void *addrptr)//converted Address
int inet_ntop (int family
void *addrptr
Char *strptr
size_t len)//size of converted Values
Success: 0
Error:-1
4. Name and address conversion
GetHostByName () Convert host name to IP address
GETHOSTBYADDR () Convert IP address to host name
#include <netbd.h>
struct hostnet *gethostbyname (const char *honstname)
Success: hostnet Type pointer
Error:-1
int getaddrinfo (const char *hostname
const CHAR *service
const struct Addrinfo *hints
struct addrinfo **result)//return result
Success: 0
Error:-1
struct Hostnet {
Char *h_name;//host Name
Char **h_aliases;
int h_addrtype;
int h_length;
Char **h_addr_list;//an array of address pointers pointing to IPV4
}
3. Function Introduction
1. Socket ()
#include <sys/socket.h>
int socket (int family,int type,int protocal)
SUCCESS: illegal socket descriptor
Error:-1;
2. Bind ()
#include <sys/socket.h>
int bind (int sockefd,struct sockaddr *my_addr,int addrlen);
Success: 0;
Error:-1
3, Listen ()
#include <sys/socket.h>
int listen (int sockfd,int backlog)
4. Accept ()
#include <sys/socket.h>
int accept (int sockfd,struct sockaddr *addr,socklen_t *addrlen);
5. Connect ()
#include <sys/socket.h>
int connect (int sockfd,struct sockaddr *serv_addr,int addrlen);
Success: 0
Error:-1
6. Send ()
int send (int sockfd,const void *msg,int len,int flags)
Success: Number of bytes Sent
Error:-1
7, recv ()
int recv (int sockfd,void *buff,int len,unsigned int flags)
Success: Number of bytes accepted
Error:-1
8, SendTo ()
int sendto (int sockfd, const void *msg,int len,unsigned int flags,struct sockaddr *to, int * tolen)
Success: Number of bytes Sent
Error:-1
9, Recvfrom ()
int recvfrom (int sockfd, const void *msg,int len,unsigned int flags,struct sockaddr *from, int * tolen)
Success: Number of bytes accepted
Error:-1
4. Simple example
- /* File NAME:SERVER.C */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #define Default_port 8000
- #define MAXLINE 4096
- int main (int argc, char** argv)
- {
- int socket_fd, CONNECT_FD;
- struct sockaddr_in servaddr;
- Char buff[4096];
- int n;
- //Initialize socket
- if ((SOCKET_FD = socket (af_inet, sock_stream, 0)) = = = 1) {
- printf ("Create socket Error:%s (errno:%d) \ n", Strerror (errno), errno);
- Exit (0);
- }
- //Initialize
- memset (&servaddr, 0, sizeof (SERVADDR));
- servaddr.sin_family = af_inet;
- SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); The //IP address is set to Inaddr_any, allowing the system to automatically get the IP address of the machine.
- Servaddr.sin_port = htons (Default_port); //Set the port to Default_port
- //Bind the local address to the socket you created
- if (Bind (SOCKET_FD, (struct sockaddr*) &servaddr, sizeof (servaddr)) = =-1) {
- printf ("bind socket Error:%s (errno:%d) \ n", Strerror (errno), errno);
- Exit (0);
- }
- //Start listening for a client connection
- if (Listen (SOCKET_FD, ten) = =-1) {
- printf ("Listen socket Error:%s (errno:%d) \ n", Strerror (errno), errno);
- Exit (0);
- }
- printf ("======waiting for client ' s request======\n");
- While (1) {
- Blocking until there is a client connection, or more wasted CPU resources.
- if (connect_fd = Accept (socket_fd, (struct sockaddr*) null, null)) = =-1) {
- printf ("Accept socket Error:%s (errno:%d)", Strerror (errno), errno);
- continue;
- }
- Accept data sent by clients
- n = recv (connect_fd, Buff, MAXLINE, 0);
- Send response data to the client
- if (!fork ()) {/ * Forbidden City * /
- if (send (CONNECT_FD, "Hello,you is connected!\n", 26,0) = =-1)
- Perror ("Send Error");
- Close (CONNECT_FD);
- Exit (0);
- }
- Buff[n] = ' + ';
- printf ("recv msg from client:%s\n", buff);
- Close (CONNECT_FD);
- }
- Close (SOCKET_FD);
- }
Client:
- /* File NAME:CLIENT.C */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #define MAXLINE 4096
- int main (int argc, char** argv)
- {
- int sockfd, N,rec_len;
- Char recvline[4096], sendline[4096];
- Char Buf[maxline];
- struct sockaddr_in servaddr;
- if (argc! = 2) {
- printf ("usage:./client <ipaddress>\n");
- Exit (0);
- }
- if ((SOCKFD = socket (af_inet, sock_stream, 0)) < 0) {
- printf ("Create socket Error:%s (errno:%d) \ n", Strerror (errno), errno);
- Exit (0);
- }
- memset (&servaddr, 0, sizeof (SERVADDR));
- servaddr.sin_family = af_inet;
- Servaddr.sin_port = htons (8000);
- if (Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <= 0) {
- printf ("Inet_pton error for%s\n", argv[1]);
- Exit (0);
- }
- if (Connect (SOCKFD, (struct sockaddr*) &servaddr, sizeof (SERVADDR)) < 0) {
- printf ("Connect error:%s (errno:%d) \ n", Strerror (errno), errno);
- Exit (0);
- }
- printf ("Send msg to server: \ n");
- Fgets (Sendline, 4096, stdin);
- if (send (SOCKFD, Sendline, strlen (Sendline), 0) < 0)
- {
- printf ("Send msg Error:%s (errno:%d) \ n", Strerror (errno), errno);
- Exit (0);
- }
- if (Rec_len = recv (SOCKFD, buf, maxline,0) = = =-1) {
- Perror ("recv error");
- Exit (1);
- }
- Buf[rec_len] = ' + ';
- printf ("Received:%s", buf);
- Close (SOCKFD);
- Exit (0);
- }
Test:
Compiling SERVER.C
Gcc-o Server Server.c
To start a process:
./server
Show Results:
======waiting for client ' s request======
And wait for the client to connect.
Compiling client.c
Gcc-o Client Server.c
Client to connect to server:
./client 127.0.0.1
Wait for input message
Send a message, type: C + +
At this point the server side sees:
The client receives the message:
In fact, you can use Telnet to test without a client:
Telnet 127.0.0.1 8000
C Socket Communication Programming