Windows Network Programming (I) Start

Source: Internet
Author: User

Windows Network Programming-Winsock (1)

Header file library of WinSock

Winsock has two major versions: Winsock 1 and WinSock 2, both of which can run on all Windows platforms except Windows CE (Winsock ce only supports Winsock 1. When developing window network programs,

Set Winsock2. H is included in the application, and the corresponding Connection Library is ws2_32.lib. The Code is as follows:

# Include <winsock2.h>

# Pragma comment (Lib, "ws2_32.lib ")

Start to initialize the Winsock library and call wsastartup (...)

int WSAStartup(

Word Wversionrequested, // The version number of the Winsock library. You can use makewor)

Lpwsadata Lpwsadata// Information about a database version loaded

);

After compiling a program using the Winsock interface, you should call the wsacleanup function. This function mainly releases all resources allocated by Winsock and cancels the Winsock call suspended by this application.

int WSACleanup(void);
Now you can write a simple Winsock network program framework:

# Include <cstdlib>

# Include <iostream>

# Include <winsock2.h>

# Pragma comment (Lib, "ws2_32.lib ")

Using namespace STD;

 

Int main (INT argc, char * argv [])

{

Wsadata;

// Initialize Winsock 2.2

Int ret = wsastartup (makeword (2, 2), & wsadata );

If (Ret! = 0)

{

// Note: Because Winsock is not loaded, we cannot use wsagetlasterror

// To identify the specific error that causes the fault. We can only judge based on the returned status

Cout <"wsastartup failed with error" <RET <Endl;

Wsacleanup ();

Return 0;

}

// Here we create a socket to connect or listen to the code.

//......

// If the program ends, wsacleanup is called.

Wsacleanup ();

System ("pause ");

Return exit_success;

}

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.