WINDOWS C language network programming quick start

xiaoxiao2021-03-06  24

C language learning, the general way is, first learn C, then C , it is best to have assembly language and microcomputer principle base, and then Visual C . In this way, spend a lot of time and endurance for learners. In the school teaching, there is no time to learn the practical technology of Windows programming.

In fact, after the C language basis, there are some basic C classes of the C class, you can learn about Windows C directly.

First, walk near Windows C

Many languages ​​make a "Hello, World!" As the first entry program, the first program in the C language is this:

#include main () {printf ("Hello, World!");

If the main function writes the main function as a parameter, it should be:

#include main (int Arge, char * argv []) {printf ("Hello, World!");

The first program of Windows C and this program are consistent in form and principles, just two points:

1. The main function received by the main function is not just the number of strings in the command line and the first address of the string.

2. Many functions of the C language can continue to use in Windows C, but the functions such as the Printf () screen display cannot continue to use. Because Windows is a multi-task operating system, the screen is no longer unique to a certain application, the Windows C application is displayed, and the API function provided by Windows is required to open your own window.

Here is the simplest, display "Hello, World!":

#include APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {MessageBox (NULL,, "the first Windows C program", MB_OK | MB_ICONASTERISK "Hello, World!");}

The main function is four:

1) Hinstance: Handle of the current instance of the program is run; 2) HPRIVINSTANCE: The handle of the previous instance; 3) LPCMDLINE: Program command line pointer; 4) ncmdshow: An integer used to specify the window display mode.

The use of these parameters will be introduced in in-depth learning.

Show Hello, Word! String, we use a MessageBox function that displays a dialog on the screen, its prototype is:

INT MessageBox (HWND HWND, LPCTSTR LPTEXT, LPCTSTR LPCAPTION, Unit Utype)

The four parameters are:

1) HWND: The handle of the parent window; 2) LPText: The pointer to the string; 3) LPCAPTION: Dialog box header string pointer; 4) uType: The type of small icon on the dialog box.

Use this function to include Windows.h header files.

Debug it, how? A "first Windows C program" dialog is popped up, there is a line above: "Hello, World!".

The world is really beautiful! !

In-depth programming:

In the C language, the function is declared, if the return value type is not specified, the default value is Void, and the main function of this program has no return value. However, in Windows programming, we'd better develop a good habit, indicate the return value type of the function, because in C , the function return value type is not default. And we will use some of the concepts of C when Windows C programming, so that it is conducive to learning in depth. The program is like this:

#include int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {MessageBox (NULL,, "the first Windows C program", MB_OK | MB_ICONASTERISK "Hello, World!"); return }

Here, we declare the type of INT, and return a value of 0, such a function can be used in a complex function call.

In this section, we have some of the concepts, handles, and pointers of the handle, and a value in the internal index table in the operating system, which prevents the application directly from accessing the object. The internal structure reflects the superiority of Windows resource management. For example, after a window is found, there should be a memory block in memory. The memory fast address in this window tends to be dynamically adjusted by the operating system, but it will not change. However, through it can access this window, it can be treated as the pointer when you are using. Second, get the host name and IP address of the local computer

Like the C language, the function is the most basic unit of Windows C programming. However, Windows C mainly uses the API function, and network programming mainly uses the API function provided by Winsock.

Winsock is the early 1990s. In order to facilitate network programming, Microsoft jointly developed a set of network programming interfaces under other companies, which is provided to users and software developers through the C language dynamic link library. It is mainly composed of Winsock.h header and dynamic link library Winsock.dll, there are currently two versions: Winsock1.1 and Winsock 2.0.

On the Win32 platform, there are many grassroots network protocols, and Winsock is the preferred interface.

To compile the Windows C program with Visual C 6.0, use the Winsock API function, first add WSOCK32.LIB to its library module, if you have shown "Error LNK2001" error when linking. The specific steps of adding WSOCK32.LIB are: Open the engineering menu, select Settings, in the pop-up Project Settings dialog box, click the Link tab, and then add WSOCK32.lib in the Object / Library Module text box.

The simplest network programming is to get the host name and IP address of this unit. This program uses WSAStart (), wsaclenaup (), getHostName (), getHostByname () four Winsock API functions, the functionality and usage method of these four functions as follows:

1. WSAStartup ():

[Function prototype]

INT Pascal Far Wsastartup (Word WversionRequired, LPWSADATA LPWSADATA); [Instructions]

Each application using Winsock must be called, and other Winsock network operation functions can only be used after the call is successful.

WVersionRequired: Indicates the Winsock version to use, this is an integer of a Word type, its high byte definition is the secondary version number, the low byte definition is the main version number.

LPWSADATA: is a pointer to WSADATA information. We generally do not use this information.

Return Value: The call successfully returns 0; otherwise, return the error message.

2. WSACleNaup ():

[Function prototype]

INT Pascal Far WSacleanup (Void);

【Instructions for use】

After Winsock is used, call the WSacleanup function to turn off the network device to release the resources it occupied.

3. gethostname ()

[Function prototype]

Int Pascal Far gethostname (Char Far * name, int namelen);

【Instructions for use】

This function can get the host name of the local host, where:

Name: The pointer used to point to the buffer of the acquired hostname.

Namelen: The size of the buffer, in bytes.

Return value: If there is no error, return 0; otherwise, return the wrong generation.

4. gethostbyname ()

[Function prototype]

Struct Hostent Far * Pascal Far GethostByname (Const Char Far * Name);

【Instructions for use】

This function can get the corresponding "host" from the hostname database.

The unique parameter Name of this function is the host name obtained by the front call function gethostname (). If there is no error, just returns a ratio pointing to the Hostent structure, which can identify a "host" list.

The HOSTENT structure is defined as follows:

Struct hostent {char far * h_name; char far far ** h_aliases; short h_addrtype; char far far ** h_addr_list;}

among them:

h_name: Host Name Address (PC). H_Aliases: A air stop array consisting of host alternate names. H_addrtype: Returns the type of address, for Winsock, this domain is always PF_INET. H_LENTH: The length of each address (number of bytes) should be 4 corresponding to the PF_INET domain. H_addr_list: The list of returned addresses should be arranged in a network sequence with a list of host addresses ending with an empty pointer.

Where h_addr_list [0] is stored is the 4 bytes of the local host, namely:

h_addr_list [0] [0] .h_addr_list [0] [1] .h_addr_list [0] [2] .h_addr_list [0] [3]

A simple message box displays the source name and IP address of the IP address as follows:

#include

INT WSA_RETURN; WSADATA WSADATA;

Hostent * host_entry; char host_name [256]; char host_address [256];

Int apientry winmain (Hinstance Hinstance, Hinstance Hprevinstance, LPSTR LPCMDLINE, INT NCMDSHOW) {WSA_RETURN = WSAStartup (0x0101, & WSADATA);

IF (WSA_RETURN == 0) {gethOstName (Host_Name, 256); host_entry = gethostByname (HOST_NAME); if (Host_Entry! = 0) {WSPrintf (Host_Address, "% D.% d.% d.% d", (Host_Entry -> h_addr_list [0] [0] & 0x00FF), (Host_Entry-> h_addr_list [0] [1] & 0x00FF), (Host_Entry-> h_addr_list [0] [2] & 0x00FF), (Host_Entry-> h_addr_list [0] [3 ] & 0x00FF));

Messagebox (null, host_address, host_name, mb_ok);}} wsacleanup (); return 0;}

In-depth programming:

When the IP address is displayed, we use the message box, and the specification is programmed to use the dialog, how to edit a dialog, many books have a presentation, editing the dialog box, which can refer to the run interface of Figure 5.

The header page GET_IP.H is as follows:

Bool apientry hostname_ipdlgpro (HWND HDLG, Uint Message, WPARAM WPARAM, LPARAM LPARAM);

This program only uses a dialog process, which generally puts the statement of this process in the header file. Source program get_ip.c: #include #include "get_ip.h" #include "resource.h" // This header will automatically generate when the resource is created, // and will automatically insert the resource generating a control identification number .int WSA_return; WSADATA WSAData; hOSTENT * host_entry; char host_name [256]; char host_address [256]; int APIENTRY WinMain (hINSTANCE hInstance, hINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {WSA_return = WSAStartup (0x0101, & Wsadata); IF (WSA_RETURN == 0) {gethOstName (Host_Name, 256); host_entry = gethostByname (Host_Name); if (Host_Entry! = 0) {WSPRINTF (Host_Address, "% D.% D.% D.% D" (Host_Entry-> h_addr_list [0] [0x00FF), (Host_Entry-> h_addr_list [0] [1] & 0x00FF), (Host_Entry-> h_addr_list [0] [2] & 0x00FF), (Host_Entry-> h_addr_list [0 ] [3] & 0x00ff));}} WSACleanup (); DialogBox (hInstance, "DIALOG1", NULL, (DLGPROC) Hostname_ipDlgPro); return 0;} BOOL APIENTRY Hostname_ipDlgPro (HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {Switch (Message) {Case WM_INITDIALOG: RETURN (TRUE); Case WM_COMMAND: IF (loword (wparam) == iDok) {setdlgitemtext (hdlg, idc_edit1, host_name); setd LGITEMTEXT (HDLG, IDC_EDIT2, HOST_ADDRESS); setdlgitemtext (HDLG, IDCANCANCEL, "OK");} if (loword (wparam) == idcancel) enddialog (hdlg, true); return; break;} return (false) } III, using the Visualc 6.0 compile the Windows C program to compile the Windows C 6.0 Generally compiled the Windows C program generally take the following four steps: New project, add code, add resources, and compile links. Below we briefly introduce the compilation process of the acquisition of the host name and IP address program described above. (1) New project 1. Start MicrosoftVisualc , then first in the [File] menu, pop up the [New] dialog box shown in Figure 1 in the [File] menu:

figure 1

2. In the [New] dialog box, the system opens the default [Engineering] tab, [Engineering] Tab There are a variety of ways of establishing a project, we select the "Win32 Application" option.

3. Enter the path to the new project (for example, f: /) in the [Position] text box, enter the project name (for example: get_ip) in the [Project] text box. 4. Select the WIN32 check box in the [Platform] list box, then click the [OK] button.

5. In the subsequent dialog box, choose the default setting, after completion, go to Figure 2 Interface:

figure 2

(2) Add code

In VisualC 6.0, source code is typically stored in the source code file and header file, which is very convenient to add source code to the project. To create a source code file for the project, you can usually follow the method:

1. Choose [Project] | [Add Project] | [New] option, pop up the [New] dialog box shown in Figure 3:

image 3

2. In the [File] tab of the dialog box, the list box on the left is selected, select the [Add Project] check box on the right side, and enter the source file name in the [File] Text box (for example:: Get_ip.c).

3. Click the [OK] button, the [New] dialog box will be closed, the user can enter the source code of the program in the newly created GET_IP.C.

4. The method of adding header files Get_IP.H is the same as described above, just in the [File] tab, the list box on the left must first "C / C Header File" option. Enter the header file name (for example: get_ip.h) in the [File] text box.

(3) Adding resources

Before adding resources, you must add a resource file in the project, and then you can use the resource editor provided by Visual C 6.0 to create a resource for the project. The specific steps are as follows:

1. Select [Project] | [Add Project] | [New] option to pop up the [New] dialog box shown in Figure 3.

2. In the [File] tab of the dialog box, check the "RSource Script" option on the left, select the [Add Project] check box in the right side, and enter the resource file name in the [File] text box (for example: get_ip .rc).

3. Click OK, after returning to the main window, select the [Insert] | [Resources] option, open the [Insert Resource] dialog, as shown in Figure 4, select the "Dialog" option in the [Resource Type] list box, click [New] button, after returning to the main window, you can use the dialog editor to edit. Edited the dialog box as shown

Figure 4

Figure 5

(4) Compiling links

After adding the source code and the resource file, you can compile the program, press Ctrl F7 key to compile, press the F7 key to connect, press CTRL F5 key to run the program. Be careful before the connection, the resource file get_ip.rc should also be compiled.

Since this program references the Winsock API function, you have to add WSOCK32.DLL before compiling connections. The specific method has been introduced, and will not be described here.

A point of view:

There are two ways to write Windows applications using C language: one is a Windows C programming method, and the other is Visual C programming. Under normal circumstances, the amount of program source code written in Visual C is small, the workload is small, the work is small, but the compiled code is large, the running speed is slightly lower; and the Windows C programming method is written The amount of program source code is large, but the code efficiency is executed. With the advancement of technology, Visual C programming methods have been widely used, but some of the network programming is high, most of which have more hardware operations, mostly use Windows C programming. In addition, learning Windows C programming also helps more about Windows's insider and Windows API. From the perspective of teaching, after the student has a C language and some other preamble courses, practical programming technology courses such as Windows C network programming can not only make students exposed to the frontier utility technology as soon as possible, but also greatly Mobilize students' enthusiasm, learn more knowledge and technology in a limited time.

figure 1

2. In the [New] dialog box, the system opens the default [Engineering] tab, [Engineering] Tab There are a variety of ways of establishing a project, we select the "Win32 Application" option.

3. Enter the path to the new project (for example, f: /) in the [Position] text box, enter the project name (for example: get_ip) in the [Project] text box.

4. Select the WIN32 check box in the [Platform] list box, then click the [OK] button.

5. In the subsequent dialog box, choose the default setting, after completion, go to Figure 2 Interface:

figure 2

(2) Add code

In VisualC 6.0, source code is typically stored in the source code file and header file, which is very convenient to add source code to the project. To create a source code file for the project, you can usually follow the method:

1. Choose [Project] | [Add Project] | [New] option, pop up the [New] dialog box shown in Figure 3:

image 3

2. In the [File] tab of the dialog box, the list box on the left is selected, select the [Add Project] check box on the right side, and enter the source file name in the [File] Text box (for example:: Get_ip.c).

3. Click the [OK] button, the [New] dialog box will be closed, the user can enter the source code of the program in the newly created GET_IP.C.

4. The method of adding header files Get_IP.H is the same as described above, just in the [File] tab, the list box on the left must first "C / C Header File" option. Enter the header file name (for example: get_ip.h) in the [File] text box.

(3) Adding resources

Before adding resources, you must add a resource file in the project, and then you can use the resource editor provided by Visual C 6.0 to create a resource for the project. The specific steps are as follows:

1. Select [Project] | [Add Project] | [New] option to pop up the [New] dialog box shown in Figure 3.

2. In the [File] tab of the dialog box, check the "RSource Script" option on the left, select the [Add Project] check box in the right side, and enter the resource file name in the [File] text box (for example: get_ip .rc). 3. Click OK, after returning to the main window, select the [Insert] | [Resources] option, open the [Insert Resource] dialog, as shown in Figure 4, select the "Dialog" option in the [Resource Type] list box, click [New] button, after returning to the main window, you can use the dialog editor to edit. Edited the dialog box as shown

Figure 4

Figure 5

(4) Compiling links

After adding the source code and the resource file, you can compile the program, press Ctrl F7 key to compile, press the F7 key to connect, press CTRL F5 key to run the program. Be careful before the connection, the resource file get_ip.rc should also be compiled.

Since this program references the Winsock API function, you have to add WSOCK32.DLL before compiling connections. The specific method has been introduced, and will not be described here.

A point of view:

There are two ways to write Windows applications using C language: one is a Windows C programming method, and the other is Visual C programming. Under normal circumstances, the amount of program source code written in Visual C is small, the workload is small, the work is small, but the compiled code is large, the running speed is slightly lower; and the Windows C programming method is written The amount of program source code is large, but the code efficiency is executed. With the advancement of technology, Visual C programming methods have been widely used, but some of the network programming is high, most of which have more hardware operations, mostly use Windows C programming. In addition, learning Windows C programming also helps more about Windows's insider and Windows API.

From the perspective of teaching, after the student has a C language and some other preamble courses, practical programming technology courses such as Windows C network programming can not only make students exposed to the frontier utility technology as soon as possible, but also greatly Mobilize students' enthusiasm, learn more knowledge and technology in a limited time.

转载请注明原文地址:https://www.9cbs.com/read-44110.html

New Post(0)