[network programming 02] simple chat program

With the basic knowledge of last socket, Network programming 01 Can write a simple chat program, casually review the basic knowledge.

1. Thread

If we want to realize that we can send and receive information at the same time, we need multiple threads, one for sending and one for receiving.

This time use CreateThread to create a thread. Function prototype

  HANDLE WINAPI CreateThread
  (   _In_opt_             LPSECURITY_ATTRIBUTES          lpThreadAttributes,
    _In_                    SIZE_T                      dwStackSize,
    _In_               LPTHREAD_START_ROUTINE          lpStartAddress,
    _In_opt_       LPVOID                            lpParameter,
    _In_          DWORD                               dwCreationFlags,
    _Out_opt_    LPDWORD                       lpThreadId
  );
Functions are simple to use when they are complex. You only need to care about what function is passed in and what function parameters are.
1. The first parameter represents the security property of the thread kernel object. Generally, NULL is passed in to indicate that the default setting is used
2. The second parameter indicates the thread stack space. Passing in 0 means using the default size
3. The third parameter indicates the address (function name) of the thread function executed by the new thread. Multiple threads can use the same function address
4. The fourth parameter is passed to the thread function.
5. The fifth parameter specifies when to call the thread. A value of 0 indicates that the thread can be called immediately after it is created.
6. The sixth parameter returns the ID number of the thread. Passing in NULL means that the thread ID number does not need to be returned
2. Server code
We encapsulate the function of sending and receiving information into two functions as threads.
  
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<WinSock2.h>
 4 #pragma comment (lib,"ws2_32.lib")
 5 SOCKET newSocket;//Global variables, sockets for communication
 6 
 7 void recvFun();//Receiving information thread
 8 void sendFun();//Send message thread
 9 void createConnect();//Create communication socket
10 
11 int main()
12 {
13     HANDLE h1, h2;//thread handle 
14     createConnect();
15     printf("Connection successful...\n");
16     //Run as soon as the thread is created
17     h1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)sendFun, NULL, 0, NULL);
18     h2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)recvFun, NULL, 0, NULL);
19     WaitForSingleObject(h1, INFINITE);//Will block until the end of the thread
20     WaitForSingleObject(h2, INFINITE);//Will block until the end of the thread
21     closesocket(newSocket);//Close socket
22     return 0;
23 }
24 void sendFun()
25 {    
26     char buf[128];
27     while (1)
28     {    
29         printf("The message you want to send:");
30         scanf("%s", buf);
31         send(newSocket, buf, strlen(buf) + 1, 0);//Send message
32     }
33 }
34 
35 void recvFun()
36 {
37     char buf[128];
38     while (1)
39     {
40         recv(newSocket, buf, 128, 0);//Receiving information
41         printf("%32s%s\n","Information received: ", buf);
42     }
43     
44 }
45 
46 void createConnect()
47 {
48     SOCKET serverSocket;//Monitored socket
49     //SOCKET newSocket;//Socket for communication
50     SOCKADDR_IN newAddr;//Save client's socket Address information
51     SOCKADDR_IN addr;//Address structure, including ip port(port)
52     WSADATA data;
53     WORD version;//socket Edition
54     int info;
55                  /*
56                  Set and initialize the version before using socket
57                  Don't worry if you don't understand
58                  */
59     version = MAKEWORD(2, 2);//Set version
60     info = WSAStartup(version, &data);
61     /*An application or DLL can only be called after a successful WSAStartup() call
62     To call further Windows Sockets API functions.
63     Initialize windows socket according to the version, and return 0 to indicate success
64     */
65     if (info != 0)
66     {
67         printf("initialization failed\n");
68         return;
69     }
70     if (LOBYTE(data.wVersion) != 2 || HIBYTE(data.wVersion) != 2)
71     {
72         printf("Load failed\n");
73         WSACleanup();
74         return;
75     }
76     //Create socket, using TCP Agreement
77     serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
78     addr.sin_addr.S_un.S_addr = htonl(ADDR_ANY);//Means any ip Come here and connect
79     addr.sin_family = AF_INET;//Use ipv4 Address of
80     addr.sin_port = htons(6666);//Set the port occupied by the application
81     bind(serverSocket, (SOCKADDR*)&addr, sizeof(SOCKADDR));//Connect socket and port 6666, receive ip binding
82     listen(serverSocket, 3);//Start to monitor whether there is a customer service terminal requesting connection,The maximum number of connections is 3
83     printf("Start listening, wait for connection..........\n");
84     int len = sizeof(SOCKADDR);
85     newSocket = accept(serverSocket, (SOCKADDR*)&newAddr, &len);
86 }

3. Client code

Client and server code are similar, but also two threads for receiving and sending information.

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<WinSock2.h>
 4 #pragma comment(lib,"ws2_32.lib")
 5 SOCKET clientSocket;//Global variables, for communication socket
 6 void createConnect();//Create socket
 7 void sendFun();//Send message thread
 8 void recvFun();//Receiving information thread
 9 int main()
10 {
11     HANDLE h1, h2;//A thread handle is actually a string of numbers used to identify a thread object
12     createConnect();//Create socket
13     //Execute immediately after thread creation
14     h1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)sendFun, NULL, 0, NULL);
15     h2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)recvFun, NULL, 0, NULL);
16     WaitForSingleObject(h1, INFINITE);//Will block until the end of the thread run
17     WaitForSingleObject(h2, INFINITE);
18     closesocket(clientSocket);//Close socket
19     return 0;
20 }
21 void createConnect()
22 {
23     SOCKADDR_IN addr;
24     int info;
25     WSADATA data;
26     WORD version;
27     //Set version, and initialization
28     version = MAKEWORD(2, 2);
29     info = WSAStartup(version, &data);
30     if (info != 0)
31     {
32         printf("initialization failed\n");
33         return;
34     }
35     if (LOBYTE(data.wVersion) != 2 || HIBYTE(data.wVersion) != 2)
36     {
37         printf("Load failed\n");
38         WSACleanup();
39         return;
40     }
41     clientSocket = socket(AF_INET, SOCK_STREAM, 0);//Create socket
42                                                    //Of the server to connect to ip,Because now the server is the local machine, so write the local machine ip
43                                                    //127.0.0.1 A special IP Address, indicating that it is local IP address
44     addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
45     //The port should be the same as the server, otherwise it cannot be found
46     addr.sin_port = htons(6666);
47     //use IPV4 address
48     addr.sin_family = AF_INET;
49     //Actively connect to the server
50     connect(clientSocket, (SOCKADDR*)&addr, sizeof(SOCKADDR));
51 }
52 
53 void sendFun()
54 {    
55     char buf[128]="who are you";
56     while (1)
57     {    
58         printf("The message you want to send: ");
59         scanf("%s", buf);
60         //send data
61         send(clientSocket, buf, strlen(buf) + 1, 0);
62     }    
63 }
64 
65 
66 void recvFun()
67 {    
68     char buf[128];
69     //Receive data sent by service
70     while (1)
71     {
72         recv(clientSocket, buf, 128, 0);//receive data 
73         printf("%32s%s\n","The information received is: ", buf);
74     }
75 }

Running results, chat can be achieved, although the interface is not good.

 

 

Learn socket programming can also achieve Trojans and other things. The principle is very simple. Let the target user run your program quietly in the background. At the other end, you can send various command operating programs to operate the user's computer and steal information. For example, you send a str="shutdown -s -f" command to force shutdown, and the target user's program receives the command and calls system(str). The target user's computer will shut down immediately.

Tags: C socket Programming Windows network

Posted on Thu, 23 Apr 2020 23:42:45 -0700 by Shad