Winsock(微軟套接字接口)的使用(1)

  套接字接口的API調用系統內核的服務(TCP/IP協議軟件)。通過這個接口我們可以實現應用進程跨越網絡的通信。

  目前,只有幾種可供應用程序使用TCP/IP的應用編程接口。其中,最著名的有美國加利福尼亞大學伯克利分校爲Berkeley UNIX操作系統定義的一種API,以及微軟在其操作系統中採用的一種套接字接口,該接口稱爲Windows Socket,簡稱爲WinSock。還有一種TLI,有興趣的可以自己去百度。

  IDE: visual studio professional 2015

  (1)make a Winsock project

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <winsock2.h>   //the #include line for the Winsock2.h header this file should be placed before the #include line for the Iphlpapi.h header file.
#include <ws2tcpip.h>
#include <iphlpapi.h>   //using the ip helper api
#include <stdio.h>

#pragma comment(lib, "Ws2_32.lib")
This is the Microsoft decline that The Winsock2.h header file internally includes core elements from the Windows.h header file, so there is not usually an #include line for the Windows.h header file in Winsock applications. If an #include line is needed for the Windows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEAN macro. For historical reasons, the Windows.h header defaults to including the Winsock.h header file for Windows Sockets 1.1. The declarations in the Winsock.h header file will conflict with the declarations in the Winsock2.h header file required by Windows Sockets 2.0. The WIN32_LEAN_AND_MEAN macro prevents the Winsock.h from being included by the Windows.h header. An example illustrating this is shown below.

As we all know, we can add the code I show in this passage at the beginning of your source to make your application support the WinSock.

#include <winsock2.h>   //This header file contains most of the Winsock functions, structures, and definitions.
#include <ws2tcpip.h>   //The Ws2tcpip.h header file contains definitions introduced in the WinSock 2 Protocol-Specific Annex document for TCP/IP 
                        //that includes newer functions and structures used to retrieve IP addresses.
#include <stdio.h>      //Stdio.h is used for standard input and output

#pragma comment(lib, "Ws2_32.lib")  //Ensure that the build environment links to the Winsock Library file Ws2_32.lib






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章