1. Learning Objectives

  1. Understand the concepts of SOCKETS in C language
  2. Understand how to use C language sockets
  3. The C language socket server is complete

directory

Is C really hard? If you don’t see this picture, you can easily learn C by breaking it into parts.

First: (1) from learning mistakes second: (2) C language is not so difficult simple development lead you to understand the process third: (3) easy to understand the first C language program fourth: (4) basic data types and variables fifth: (5) C language variables, constants and operations sixth: (9) The basic array is not so simple. (9) THE TWO-DIMENSIONAL array and loop nesting of C language. (10) The pointer of C language is originally like this. (11) C language custom function is really very simple twelfth :(12) the original structure is such a thing thirteenth :(13) socket server written

C language novice 100 error solutions

recommended

Welcome everyone to follow the official account, wechat search “blue oil chicken”, every official account reaches 1024 or multiple of 1024 will be lucky draw a mechanical keyboard + 2 IT books yo ~\

How to use a socket

Hit a flu shot: don’t understand the concept will also use, now don’t understand later will certainly understand. If the reader is starting to learn this article through my basic tutorial, I personally recommend that you familiarize yourself with the knowledge as much as possible before learning about socket, socket design, and basic syntax and features, otherwise it will cause some problems. If really learned what problem can add group to ask me ~

A socket, also known as a socket, is a careful endpoint that different hosts listen to and send in a computer network. This endpoint is an abstract concept, and like all designs that do not physically exist, it is born under a rule.

2.1 use the socket

The following code is found on the network code, their own partial modification. (Lazy writing, ha ha ha) This content only focuses on the use of process, biased to application, too much theoretical knowledge is not emphasized. For beginners to learn the socket my personal advice is to know how to “replace” first, do a “replace” to complete the whole process to a better understanding of the problem, but for beginners, some additional extension knowledge every novice does not know, if you really need to explain the socket communication, will design a lot of network layer, So we first learn how to use socket, and then to comb these knowledge.

Because the socket practice content for some novice steps too cumbersome, in this is divided into two, one for the server, one for the client to communicate, compared to you after learning the server to view the client code will feel a flash in front of you, socket is trouble to use just ~ I wish you code yunchang Long!

Socket is based on TCP/IP. Some of you may be familiar with TCP/IP. It’s true that TCP/IP is a common word when we learn programming, it’s a protocol, and what is a protocol? Agreement means we are doing one thing, some provisions of our regulations, standards, convenient communication, communication and TCP/IP is one of the agreement, once again, we only need the socket is based on TCP/IP protocol, because in the current tutorial, talk about the agreement to one part of the reader may have a reading disorder, this is very normal. We can communicate with sockets without knowing TCP/IP, because the socket function we use is based on TCP/IP, which means we just need to know how to use sockets.

To write a C Windows socket, you need to go through several steps. First, initialize WSAStartup, create the socket, bind the socket, and bind the configuration information. If there is a connection, connect. Then use accept to receive the request. After receiving the request, you can choose to accept recV or send to send data. WSACleanup was eventually shut down.

2.2 WSAStartup Initialization

WSAStartup is initialized. The WSAStartup method receives two parameters, one the version number of WinSock2 and the other a pointer to WSADATA. We need to create a WSADATA object with the following code:

WSADATA wsaData;
Copy the code

The WSADATA structure is used to store the information returned after WSAStartup initialization. This information is stored after WSAStartup initialization because it uses a pointer, in other words an address.

The first argument WSAStartup receives is the version number, which can be generated directly using MAKEWORD, where MAKEWORD(1, 1) indicates that the version number is selected as 1. So the WSAStartup initialization code can be written as:

WSAStartup(MAKEWORD(1.1), &wsaData)
Copy the code

Since WSAStartup equals 0, it means initialization failure, and initialization failure means exit program, we can write as:

WSADATA wsaData;
if (WSAStartup(MAKEWORD(1.1), &wsaData) ! =0)
{
	return 0;
}
Copy the code

2.3 the socket creation

The socket is created using the Socket method. The socket accepts three parameters: the IP type, the communication type, and the last parameter that can be passed using the default type. The IP type is usually PF_INET for IPV4, the communication type is TCP, and the last parameter is 0 for the default option to match the IP type with the communication type. The code is as follows:

SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
Copy the code

After the socket is created, check whether the socket is created successfully. If the socket is not created successfully, -1 is displayed:

if (slisten == - 1)
	{
		printf("socket error !");
		return 0;
	}
Copy the code

2.4 the IP

Next, start binding the listening IP address. Create the sockadDR_IN structure variable.

struct sockaddr_in sin;
Copy the code

INADDR_ANY indicates the local host and 6666 indicates the listening port.

sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
Copy the code

Then use bind to bind; Bind accepts three parameters: the socket to be created, the IP information to bind, and the length of the IP information. If the bind fails, return -1.

struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
if (bind(slisten, (LPSOCKADDR)&sin.sizeof(sin)) == SOCKET_ERROR)
{
	printf("bind error !");
	return 0;
}
Copy the code

Listen accepts two values: socket and queue number (10). The code is:

if (listen(slisten, 5) == SOCKET_ERROR)
{
	printf("listen error !");
	return 0;
}
Copy the code

2.5 Receiving Information

Accept Accepts three parameters. The first is the socket, the second is the pointer to the sockADDR variable, and the third is the length of the received SOckADDR. The code is:

struct sockaddr_in remoteAddr;
int nAddrlen = sizeof(remoteAddr);
sClient = accept(s, (SOCKADDR *)&remoteAddr, &nAddrlen);
Copy the code

After using ACCPET, the code will wait until there is a link. Then recV is used to receive the text message sent by the client. Recv takes four parameters, the first is the established communication, followed by an array, where the received data is stored, and then the cache size. The last parameter is usually set to 0. The code is:

char revData[255];
int ret = recv(sClient, revData, 255.0);
printf(revData);
Copy the code

In the above RECV functions, sClient is the communication established using ACCPET, revData is the cache area for receiving information, and 255 is the length.

A data is then sent to the client, and the user responds to the client’s request for information. You can use SEND to send data to an established communication channel. The SEND function receives four parameters. The first parameter is the established communication, the second parameter is the data to be sent, the third parameter is the length of the data to be sent, and the last parameter is usually set to 0. The code is:

char * sendData = "Hello duck, I am CSDN 1_bit, ID is A757291228~\n";
send(sClient, sendData, strlen(sendData), 0);
Copy the code

In the recV function above, sClient is the communication established using ACCPET, sendData is the data to be sent, 255 is the length. Finally, call the method to close the established communication:

closesocket(sClient);
closesocket(slisten);
WSACleanup();
Copy the code

Since this is a one-time communication, the program will be closed after running. Here we add the stop command before the code return0:

system("pause");
Copy the code

All dependency reference headers are as follows:

#include <winsock2.h>
#include <windows.h>
#include<stdio.h>
#include<stdlib.h>
Copy the code

The complete code is as follows:

#include <winsock2.h>
#include <windows.h>
#include<stdio.h>
#include<stdlib.h>
 
int main(int argc, char* argv[])
{
	// Initialize WSADATA
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2.2), &wsaData) ! =0)
	{
		return 0;
	}
 
	/ / create scoket
	SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (slisten == - 1)
	{
		printf("socket error !");
		return 0;
	}
 
	// IP address of the bound port
	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port = htons(8888);
	sin.sin_addr.S_un.S_addr = INADDR_ANY;
	if (bind(slisten, (LPSOCKADDR)&sin.sizeof(sin)) == SOCKET_ERROR)
	{
		printf("bind error !");
		return 0;
	}
 
	// If listening fails, return
	if (listen(slisten, 5) == SOCKET_ERROR)
	{
		printf("listen error !");
		return 0;
	}
 

	SOCKET sClient;
	struct sockaddr_in remoteAddr;
	int nAddrlen = sizeof(remoteAddr);
	sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);
	
	char revData[255];
	int ret = recv(sClient, revData, 255.0);
	printf(revData);
	// Send a message
	char * sendData = "Hello duck, I am CSDN 1_bit, ID is A757291228~\n";
	send(sClient, sendData, strlen(sendData), 0);
	
	closesocket(sClient);
	closesocket(slisten);
	WSACleanup();
	
	system("pause");
	return 0;
}
Copy the code

If devc is used to copy code, then go to Compile -> Compile options:



Then add the following parameters to the window that appears:

conclusion

1. Understood the basic programming process of C language socket 2. Understood the following steps to write C language socket under Windows: initialize WSAStartup, create socket socket through initialization, bind with binding information, and bind configuration information. If there is a connection, connect. Then use accept to receive the request. After receiving the request, you can choose to accept recV or send to send data. WSACleanup was eventually shut down.