[network programming 01] basic knowledge of socket - simple network communication program

1. What is socket

Socket is simply a combination of IP address and port, which can communicate with the application of remote host. A host can be determined by IP address, and an application can be determined by port. IP + port can completely determine an application of a host. Socket originated from UNIX, similar to a special file, can be opened, closed, read and write operations. In a word, with socket, you can communicate with hosts on the network.

2.TCP/UDP protocol

In order to carry out network communication, it is necessary to carry out certain rules. TCP/UDP is such a protocol, which stipulates the rules of communication.

TCP is a reliable, connection oriented two-way data transmission protocol. Reliability means that data will not be duplicated or lost. Whenever the sender sends a data to the receiver, if the receiver receives the data, it will send a confirmation message to the sender to indicate that "I have received the data, you can send the next data". After receiving the confirmation message, the sender will send the next data. In this way, you can be sure that the information is correct. Two way transmission means that both parties can act as sender or receiver.

UDP is an unreliable, connectionless two-way transport protocol. UDP protocol only sends data, does not confirm whether you have received it. It is only responsible for sending, not for confirming, so it is unreliable. UDP is suitable for transmitting video and so on. Even if one or two frames of video are lost, it will not have a great impact.

socket can be based on either TCP or UDP, and can be selected according to the demand.


3. A simple communication program

Use a simple example to illustrate the use of socket. The program written with socket is generally divided into two parts, one is the server and the other is the client

The following describes the server-side creation process

1). A socket is required to communicate. The function to create a socket is


1 int socket(int af, int type, int protocol);

af: indicates the address family, commonly used are af ﹣ INET for IPV4 address, af ﹣ inet6 for IPV6 address

type: the commonly used transmission types are sock'stream, sock'dgram, streaming transmission and message transmission

protocol: commonly used protocols are ipproto? TCP and ipptoto? UDP, which represent TCP and UDP protocols respectively

Returns a socket descriptor, which is an integer.

2). Use bind() function to determine various socket attributes

1 int bind(int sock, struct sockaddr *addr, socklen_t addrlen);  

sock: socket to bind

addr: SOCKADDR address structure, which contains the used protocol, IP address, port, etc. Make your own settings

addrlen: the size of SOCKADDR, which can be obtained by sizeof()

The following code shows the process of creating a socket and binding

1 //Use IPV4 Address, TCP Agreement
2 serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
4 addr.sin_addr.S_un.S_addr = htonl(ADDR_ANY);//Means any ip Come here and connect
5 addr.sin_family = AF_INET;//Use IPV4 address
6 addr.sin_port = htons(6666);//Use port 6666
7 bind(serverSocket, &addr, sizeof(SOCKADDR));//Set socket and port 6666 to receive ip binding

3). listen function listening

After setting the properties, the server can start to monitor whether there is a client request connection.

Function prototype

1 int listen(int sock, int backlog); 

Socket: sock et

backlog: how many customer service terminals are allowed to connect

4). accept function waits for connection

accept is a blocking function. If there is no client clearing the connection, it will wait here all the time

1 int accept(int sock, struct sockaddr *addr, socklen_t *addrlen); 

sock: socket,

addr:SOCKADDR structure

Addrlen: the length of addr, which can be obtained by sizeof

Pay attention to the return value of this function. It will return a new socket. This new socket is used to communicate with the client. The previous socket is the listening socket. Be clear.

5). send/recv send / receive information

After successfully connecting with the client, you can communicate. The functions that can be communicated are write/read,send/recv, etc. here, send/recv is introduced

1 int send(int sockfd, const char *buf, size_t len, int flags);
3 int recv(int sockfd, char*buf, size_t len, int flags);

sockfd: socket

buf: buffer to send data

len: length of data sent

flags: flag, generally zero

6). closesocket function closes socket

closesocket() close socket

Here is a complete server-side code

 1 #include<stdio.h>
 2 #include<WinSock2.h>
 3 #include<windows.h>
 4 #pragma comment (lib,"ws2_32.lib")
 5 int main()
 6 {
 7     SOCKET serverSocket;//Monitored socket
 8     SOCKET newSocket;//Socket for communication
 9     SOCKADDR_IN newAddr;//Save client's socket Address information
10     SOCKADDR_IN addr;//Address structure, including ip port(port)
12     WSADATA data;    
13     WORD version;//socket Edition
14     int info;
15     char buf[32];//Data buffer
16     /*
17        Set and initialize the version before using socket
18        Don't worry if you don't understand
19     */
20     version = MAKEWORD(2, 2);//Set version
21     info = WSAStartup(version, &data);
22     /*An application or DLL can only be called after a successful WSAStartup() call
23            To call further Windows Sockets API functions.
24         Initialize windows socket according to the version, and return 0 to indicate success
25     */
27     if (info != 0)
28     {
29         printf("initialization failed\n");
30         return -1;
31     }
32     if (LOBYTE(data.wVersion) != 2 || HIBYTE(data.wVersion) != 2)
33     {    
34         printf("Failed to load\n");
35         WSACleanup();
36         return 0;
37     }
38      //Create socket, using TCP Agreement
39     serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
40     addr.sin_addr.S_un.S_addr = htonl(ADDR_ANY);//Means any ip Come here and connect
41     addr.sin_family = AF_INET;//Use ipv4 Address
42     addr.sin_port = htons(6666);//Set the port occupied by the application
43     bind(serverSocket, &addr, sizeof(SOCKADDR));//Connect socket and port 6666, receive ip binding
44     listen(serverSocket, 3);//Start to monitor whether there is a customer service terminal requesting connection
45     printf("Start listening, wait for connection..........\n");
46     int len = sizeof(SOCKADDR);
47     newSocket=accept(serverSocket, (SOCKADDR*)&newAddr,&len);
48     sprintf(buf, "Welcome:%s User connection for", inet_ntoa(newAddr.sin_addr));
49     send(newSocket, buf, 32, 0);//Send message
50     printf("Connection successful, start sending message..........\n");
51     recv(newSocket, buf, 32, 0);//Receiving information
52     printf("The received information is:%s\n", buf);
53     closesocket(newSocket);//Close socket
54 }

Operation results



Client example

The client is different from the server. The server is waiting for connection, while the client is active. Therefore, the client does not listen or accept to wait for connection.

The client has a connect function to actively connect to the server. The rest are similar

1 int connect(int sock, struct sockaddr *serv_addr, socklen_t addrlen);

Socket: sock et

Serv? Addr: SOCKADDR structure

addrlen:serv_addr length, which can be obtained by sizeof

Client code


 1 #include<stdio.h>
 2 #include<Windows.h>
 3 #include<Windows.h>
 4 #pragma comment(lib,"Ws2_32.lib")
 6 int main()
 7 {
 8     SOCKET clientSocket;
 9     SOCKADDR_IN addr;
10     int len;
11     char buf[32];
12     int info;
13     WSADATA data;
14     WORD version;
15     //Set version, and initialization
16     version = MAKEWORD(2, 2);
17     info = WSAStartup(version, &data);
18     if (info != 0)
19     {
20         printf("initialization failed\n");
21         return -1;
22     }
23     if (LOBYTE(data.wVersion) != 2 || HIBYTE(data.wVersion) != 2)
24     {
25         printf("Failed to load\n");
26         WSACleanup();
27         return 0;
28     }
30     clientSocket = socket(AF_INET, SOCK_STREAM, 0);//Create socket
31     //Of the server to connect to ip,Because now the server is the local machine, so write the local machine ip
32     // A special IP Address, indicating that it is local IP address
33     addr.sin_addr.S_un.S_addr = inet_addr("");
34     //The port should be the same as the server, otherwise it cannot be found
35     addr.sin_port = htons(6666);
36     //use IPV4 address
37     addr.sin_family = AF_INET;
38     //Actively connect to the server
39     connect(clientSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR));
40     //Receive data sent by service
41     recv(clientSocket, buf, 32, 0);//receive data
42     printf("The message sent by the server is:%s\n", buf);
43     sprintf(buf, "%s","Hello, server");
44     //send data
45     send(clientSocket, buf, 32, 0);
46     //Close socket
47     closesocket(clientSocket);
48     return 0;
50 }


Start the server before starting the client. A simple communication is done





Take this simple example and have a preliminary understanding of socket, at least learn how to use it.

Next time, write a simple chat program with socket to further deepen the understanding of socket.

Keywords: C socket Windows network Unix

Added by munuindra on Wed, 15 Apr 2020 11:46:48 +0300