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 the main function is written 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, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
MessageBox (NULL, "Hello, World! "," First Windows C program ", MB_OKMB_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 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, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
MessageBox (NULL, "Hello, World! "," First Windows C program ", MB_OKMB_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 governance. 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 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 WSAData;

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

Int APIENTRY WinMain (HINSTANCE 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 wParam, LPARAM 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,
// It is automatically generated when the resource is inserted.

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.