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

来源:互联网 发布:淘宝网男士短袖 编辑:程序博客网 时间:2024/06/05 13:24

  套接字接口的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
原创粉丝点击