Quick Start to C language network programming in Windows

Source: Internet
Author: User
Tags name database
The general way to learn C language is to first learn C and then C ++. It is best to have the basis of assembly language and microcomputer principles, followed by Visual C ++. This method takes a lot of time and endurance for learners. In school teaching, there is no time to thoroughly study the practical technology of Windows programming.

In fact, with the basic C language, there are some basic concepts of C ++ classes, you can directly learn Windows C programming.

I. Windows C Language

A "Hello, world!" is displayed in many languages !" As the first entry program, the first program in C language is as follows:

# Include <stdio. h>
Main ()
{
Printf ("Hello, world !");
}

If you write the main function as a main function with parameters, it should be:

# Include <stdio. h>
Main (INT arge, char * argv [])
{
Printf ("Hello, world !");
}

The first program in Windows C is consistent with the program in terms of form and principle, but there are two differences:

1. The parameters received by the main function are not only the number of strings in the command line and the first address of the string.

2. Many functions in C language can be used in Windows C, but functions such as printf () screen display cannot be used any more. Windows is a multi-task operating system, and the screen is no longer exclusive to an application. To display strings in Windows C applications, you must use the API functions provided by windows to open your own window.

The following is the simplest example: "Hello, world !" Windows C program:

# Include <windows. h>
Apientry winmain (hinstance, hinstance hprevinstance,
Lpstr lpcmdline, int ncmdshow)
{
MessageBox (null, "Hello, world! "," First Windows C program ", mb_ OK | mb_iconasterisk );
}

The main function has four parameters:

1) hinstance: handle of the current instance when receiving the program running;
2) hprivinstance: the handle of the previous instance;
3) lpcmdline: The program command line pointer;
4) ncmdshow: an integer used to specify the window display mode.

We will introduce the use of these parameters in deep learning.

Show hello, word! String, we use a MessageBox function, which will display a dialog box on the screen. Its prototype is:

Int MessageBox (hwnd, lpctstr lptext, lpctstr lpcaption, unit utype)

The four parameters are:

1) hwnd: handle of the parent window;
2) lptext: the pointer of the string to be displayed;
3) lpcaption: pointer to the title string of the dialog box;
4) utype: the type of the small icon displayed in the dialog box.

Use this function to include the windows. h header file.

How about debugging? The window displays the "first Windows C program" dialog box with a line on it: "Hello, world !".

The world is really beautiful !!

Deep programming:

In C language, if the function declaration does not specify the return value type and the default value is void, the main function of this program will not return the value. However, in Windows programming, we 'd better develop a good habit of specifying the type of the function's return value, because in C ++, the function's return value type cannot be default. In Windows C Programming, we still use some concepts of C ++. Doing so will facilitate further study in the future.

A standardized program should be like this:

# Include <windows. h>
Int apientry winmain (hinstance, hinstance hprevinstance,
Lpstr lpcmdline, int ncmdshow)
{
MessageBox (null, "Hello, world! "," First Windows C program ", mb_ OK | mb_iconasterisk );
Return 0;
}

Here, the declared type is int type, and a value of 0 is returned, so that the function can be used in a complex function call.

In this section, we have mentioned the concept of a handle in several parts. The concept of a handle is different from that of a pointer. It is used as a value in the internal index table of the operating system, this prevents applications from directly accessing the internal structure of the name object, reflecting the superiority of Windows resource management. For example, after a window is opened, a memory block in the corresponding memory is properly located. The fast memory address of the window will be dynamically adjusted by the operating system, but it will not change. However, you can access this window through it, so you can treat it as a pointer when using it.
2. Obtain the Host Name and IP address of the Local Computer

Like C, functions are the most basic unit of Windows C programming. However, Windows C mainly uses API functions, while network programming mainly uses the API functions provided by Winsock.

Winsock was developed in early 1990s. To facilitate network programming, Microsoft and several other companies jointly developed a set of network programming interfaces for Windows, it is provided to users and software developers through the dynamic link library of C language, mainly by Winsock. h header file and dynamic link library Winsock. it consists of two versions: winsock1.1 and winsock2.0.

On the Win32 platform, Winsock is the preferred interface for accessing a large number of grass-roots network protocols.

Compile a Windows C program using Visual C ++ 6.0. When using the Winsock API function, add wsock32.lib to its library module, the error "error lnk2001" is displayed. To add wsock32.lib, go to the project menu and select Settings. In the displayed Project Settings dialog box, click the link tab and add wsock32.lib to the object/Library module text box.

The simplest network programming method is to obtain the Host Name and IP address of the local machine. This program uses four Winsock API functions: wsastart (), wsaclenaup (), gethostname (), and gethostbyname, the functions and usage of these four functions are described as follows:

1. wsastartup ():

[Function prototype]

Int Pascal far wsastartup (word wversionrequired, lpwsadata );

[Instructions]

Every application that uses Winsock must call the wsastart function, and other Winsock network operation functions can be used only after the call is successful.

Wversionrequired: <input> indicates the Winsock version to be used. This is an integer of the Word type. The high byte defines the secondary version number, and the low byte defines the primary version number.

Lpwsadata: <output> is a pointer to wsadata. We generally do not use this document.

Return Value: 0 if the call is successful. Otherwise, an error message is returned.

2. wsaclenaup ():

[Function prototype]

Int Pascal far wsacleanup (void );

[Instructions]

After Winsock is used, you need to call the wsacleanup function to disable the network device to release the resources it occupies.

3. gethostname ()

[Function prototype]

Int Pascal far gethostname (char far * Name, int namelen );

[Instructions]

This function can obtain the Host Name of the local host, where:

Name: <output> pointer to the buffer zone of the obtained host name.

Namelen: <input> buffer size, in bytes.

Return Value: If no error is returned, 0 is returned. Otherwise, is the error generation returned.

4. gethostbyname ()

[Function prototype]

Struct hostent far * Pascal far gethostbyname (const char far * Name );

[Instructions]

This function can obtain the corresponding "host" from the host name database ".

The unique parameter name of this function is the host name obtained by calling the function gethostname. If no error occurs, a batch needle pointing to the hostent structure is returned, which can identify a "host" list.

The hostent structure is defined as follows:

Struct hostent
{
Char far * h_name;
Char far ** h_aliases;
Short h_addrtype;
Char far ** h_addr_list;
}

Where:

H_name: <input> host name address (PC ).
H_aliases: an air-Stop array consisting of the standby host name.
H_addrtype: Type of the returned address. For WinSock, this field is always pf_inet.
H_lenth: the length of each address (number of bytes), which corresponds to 4 in the pf_inet field.
H_addr_list: List of host addresses that should end with a null pointer. The returned addresses are arranged in network order.

H_addr_list [0] stores the 4-byte IP address of the local host, that is:

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

A simple source code that displays host names and IP addresses in a message box is as follows:

# Include <Winsock. h>

Int wsa_return;
Wsadata;

Hostent * host_entry;
Char host_name [2, 256];
Char host_address [1, 256];

Int apientry winmain (hinstance, hinstance hprevinstance,
Lpstr lpcmdline, int ncmdshow)
{
Wsa_return = maid (0x0101, & wsadata );

If (wsa_return = 0)
{
Gethostname (host_name, 256 );
Host_entry = gethostbyname (host_name );
If (host_entry! = 0)
{
Wsprintf (host_address, "% 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;
}
 

Deep programming:

When the IP address is shown above, we use a message box. A standardized programming should use a dialog box. Many books have introduced how to edit a dialog box, for the edit dialog box, see Figure 5.

The header file get_ip.h is as follows:

Bool apientry hostname_ipdlgpro (hwnd hdlg, uint message, wparam, lparam );

This program only uses a dialog box process. Generally, the declaration of this process is put in the header file.

Source program get_ip.c:

# Include <winsock2.h>
# Include "get_ip.h"
# Include "resource. H" // This header file is automatically generated when resources are created,
// The Control ID is automatically generated when the resource is inserted.
Int wsa_return;
Wsadata;

Hostent * host_entry;
Char host_name [2, 256];
Char host_address [1, 256];

Int apientry winmain (hinstance, hinstance hprevinstance,
Lpstr lpcmdline, int ncmdshow)
{
Wsa_return = maid (0x0101, & wsadata );
If (wsa_return = 0)
{
Gethostname (host_name, 256 );
Host_entry = gethostbyname (host_name );
If (host_entry! = 0)
{
Wsprintf (host_address, "% 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 ));
}
}
Wsacleanup ();
Dialogbox (hinstance, "dialog1", null, (dlgproc) hostname_ipdlgpro );
Return 0;
}

Bool apientry hostname_ipdlgpro (hwnd hdlg, uint message,
Wparam, lparam)
{
Switch (Message)
{
Case wm_initdialog:
Return (true );
Case wm_command:
If (loword (wparam) = idok)
{
Setdlgitemtext (hdlg, idc_edit1, host_name );
Setdlgitemtext (hdlg, idc_edit2, host_address );
Setdlgitemtext (hdlg, idcancel, "OK ");
}
If (loword (wparam) = idcancel)
Enddialog (hdlg, true );
Return (true );
Break;
}
Return (false );
}

  Iii. Use VisualC ++ 6.0 to compile a Windows C program

To compile a Windows C program using Visual C ++ 6.0, follow these four steps: creating a project, adding Code, adding resources, and compiling links. Next, we will briefly introduce the compilation process of the program described above to obtain the Host Name and IP address of the local machine:

(1) create a project

1. Start microsoftvisualc ++ and select the new command in the File menu. The new dialog box shown in 1 is displayed:



Figure 1

2. in the new dialog box, the default project tab is opened. The list box on the left of the Project tab contains multiple ways to create a project. Select the "Win32 application" option.

3. Enter the path (for example, F:/) of the new project in the location text box, and enter the project name (for example, get_ip) in the project text box ).

4. Select the Win32 check box in the platform list box and click OK.

5. In the subsequent dialog box, select the default settings. After the settings are complete, the page shown in Figure 2 is displayed:


Figure 2

(2) Add code

In Visual C ++ 6.0, the source code is generally stored in the source code file and header file. It is very convenient to add the source code to the project. To create a source code file for the project, follow these steps:

1. Select [project] | [add project] | [new]. The [new] dialog box shown in Figure 3 is displayed:


Figure 3

2. on the files tab of the dialog box, select the C ++ source file option in the list box on the left, and select the Add project check box on the right, enter the source file name (for example, get_ip.c) in the file text box ).

3. Click OK. The new dialog box is closed. You can enter the source code of the program in the newly created get_ip.c file.

4. The method for adding the header file get_ip.h is the same as that described above, but on the file tab, select "C/C ++ header file" in the list box on the left. In the file text box, enter the header file name (for example, get_ip.h ).

(3) Add resources

Before adding resources, you must first add a resource file in the project, and then create a resource for the project using the resource editor provided by Visual C ++ 6.0. The procedure is as follows:

1. Select project, add project, and create. The create dialog box is displayed, as shown in figure 3.

2. on the files tab of the dialog box, select the rsource script option in the list box on the left, select the Add project check box on the right, and enter the resource file name in the file text box (for example: get_ip.rc ).

3. click OK. Return to the main window and select insert | resource to open the insert resource dialog box, as shown in 4. In the resource type list box, select the dialog option, click the new button and return to the main window. You can use the dialog box editor to edit it. Edit dialog box


Figure 4

Figure 5

(4) Compile the link

After the source code and resource files are added, You can compile and connect the program. You can press Ctrl + F7 to compile the program, press F7 to connect, and press Ctrl + F5 to run the program. Note that the resource file get_ip.rc must be compiled before connection.

Since this program references the Winsock API function, you must add wsock32.dll before compiling the connection. The specific method has been described earlier and will not be repeated here.

One point:

There are two methods to write Windows applications using C language: one is Windows C programming, and the other is Visual C ++ programming. In general, Visual C ++ programming requires a small amount of source code, a small amount of work during development, and a small amount of work, but the compiled code is large, the running speed is slightly lower, while the source code of the program written in Windows C Programming Method is large, but the executable code efficiency is high. With the advancement of technology, Visual C ++ programming has been widely used. However, for example, network programming and other programs with high speed requirements and many hardware operations, most of them are developed using Windows C programming. In addition, learning Windows C programming helps you gain a deeper understanding of Windows's insider information and Windows APIs.

From the teaching point of view, after students have the basic knowledge of C language and other leading courses, they can directly go to practical programming technology courses such as Windows C network programming, it not only allows students to get in touch with cutting-edge practical programming technologies as early as possible, but also greatly mobilizes students' learning enthusiasm and learns more knowledge and technology in a limited time.


Figure 1

2. in the new dialog box, the default project tab is opened. The list box on the left of the Project tab contains multiple ways to create a project. Select the "Win32 application" option.

3. Enter the path (for example, F:/) of the new project in the location text box, and enter the project name (for example, get_ip) in the project text box ).

4. Select the Win32 check box in the platform list box and click OK.

5. In the subsequent dialog box, select the default settings. After the settings are complete, the page shown in Figure 2 is displayed:


Figure 2

(2) Add code

In Visual C ++ 6.0, the source code is generally stored in the source code file and header file. It is very convenient to add the source code to the project. To create a source code file for the project, follow these steps:

1. Select [project] | [add project] | [new]. The [new] dialog box shown in Figure 3 is displayed:


Figure 3

2. on the files tab of the dialog box, select the C ++ source file option in the list box on the left, and select the Add project check box on the right, enter the source file name (for example, get_ip.c) in the file text box ).

3. Click OK. The new dialog box is closed. You can enter the source code of the program in the newly created get_ip.c file.

4. The method for adding the header file get_ip.h is the same as that described above, but on the file tab, select "C/C ++ header file" in the list box on the left. In the file text box, enter the header file name (for example, get_ip.h ).

(3) Add resources

Before adding resources, you must first add a resource file in the project, and then create a resource for the project using the resource editor provided by Visual C ++ 6.0. The procedure is as follows:

1. Select project, add project, and create. The create dialog box is displayed, as shown in figure 3.

2. on the files tab of the dialog box, select the rsource script option in the list box on the left, select the Add project check box on the right, and enter the resource file name in the file text box (for example: get_ip.rc ).

3. click OK. Return to the main window and select insert | resource to open the insert resource dialog box, as shown in 4. In the resource type list box, select the dialog option, click the new button and return to the main window. You can use the dialog box editor to edit it. Edit dialog box


Figure 4

Figure 5

(4) Compile the link

After the source code and resource files are added, You can compile and connect the program. You can press Ctrl + F7 to compile the program, press F7 to connect, and press Ctrl + F5 to run the program. Note that the resource file get_ip.rc must be compiled before connection.

Since this program references the Winsock API function, you must add wsock32.dll before compiling the connection. The specific method has been described earlier and will not be repeated here.

One point:

There are two methods to write Windows applications using C language: one is Windows C programming, and the other is Visual C ++ programming. In general, Visual C ++ programming requires a small amount of source code, a small amount of work during development, and a small amount of work, but the compiled code is large, the running speed is slightly lower, while the source code of the program written in Windows C Programming Method is large, but the executable code efficiency is high. With the advancement of technology, Visual C ++ programming has been widely used. However, for example, network programming and other programs with high speed requirements and many hardware operations, most of them are developed using Windows C programming. In addition, learning Windows C programming helps you gain a deeper understanding of Windows's insider information and Windows APIs.

From the teaching point of view, after students have the basic knowledge of C language and other leading courses, they can directly go to practical programming technology courses such as Windows C network programming, it not only allows students to get in touch with cutting-edge practical programming technologies as early as possible, but also greatly mobilizes students' learning enthusiasm and learns more knowledge and technology in a limited time.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.