Windows Network Programming learning-Winsock API

Source: Internet
Author: User
WinSock Winsock is a network programming interface provided on the Win32 platform and has nothing to do with the specific network protocol (that is, it supports multiple network protocols). It draws on the Berkeley (BSD) on the UNIX platform) socket programming (UNIX socket programming is very similar to WinSock programming ). Although Winsock has nothing to do with the protocol, we still need to know some characteristics of the network protocol during programming, such as message-oriented, connection-free, and route selection. Message-oriented Based on different network protocols, we can divide them into message boundary and message-Free Boundary protection. Generally, the protocol without message boundary protection is called "stream-based protocol ". Assume that the sender sends several messages of different sizes, such as 128 bytes and 256 bytes, and the receiver reads the data packet of one message twice at a time, even if all these packets exist in the network stack. The packets sent by UDP protocol that we are familiar with are message boundary-protected (the same is true for the datagram of the same IP address ). If the message is in a stream-based protocol, because there is no protection boundary for the message, the system may split the large message or combine the small one and then return as much data as possible. The well-known TCP protocol is stream-based. Connection-oriented or connectionless A connection-oriented protocol establishes a virtual path before data exchange, and connection-oriented protocols usually provide certain reliability assurance services (the cost is to maintain the connection overhead ). The connectionless protocol is only responsible for directly shipping data out of other services. It is faster than sending mail like a postal service, although it lacks reliability. The TCP protocol in general is connection-oriented, while UDP is non-connection. You can select which Protocol to use for communication based on different scenarios and requirements. Routing The router will discard all the non-route protocol packets (for example, the netbeui protocol ). If we designProgramIf there are different networks (of course these networks are connected through routers), we need to select a routable protocol. The first push is of course TCP/IP. Wsastartup Function Before using WinSock programming, you must first load the Winsock library, that is, call the wsastartup function (the main difference between this function and UNIX socket ). Int wsastartup (word wversionrequested, lpwsadata). The first parameter of this function specifies the socket version requested by the program, the high byte indicates the sub-version and the low byte indicates the master version (you can use the macro makewode () to obtain the wversionrequested ); the operating system uses the second parameter to return the request's socket version information (only wversion and whighversion are useful ). When an application calls the wsastartup function, the operating system searches for the corresponding socket Library Based on the requested socket version and binds the socket Library to the application. In the future, the application can call other socket functions in the requested socket library. After the function is successfully executed, 0 is returned.
   code highlighting produced by actipro codehighlighter (freeware) 
http://www.CodeHighlighter.com/
--> 1 wversionrequested = makeword ( 2 , 2 );
2 err = wsastartup (wversionrequested, & wsadata );

let's take a look. net C # language is how to call the wsastartup function, of course we are using C # does not need to display open Winsock library ,. net helped us encapsulate it. Use reflector to find the system. net. Socket class (my name is. net3.5 ). View Public socket (addressfamily, sockettype, protocoltype) the following two sentences are found:

  1 Initializesockets ();
2 This. M_handle=Safeclosesocket. createwsasocket (addressfamily, sockettype, protocoltype );
3  

Among them,. m_handle is a safeclosesocket class (in fact, its ancestor is the safehandle class, and it is attached with the security handle and emergency termination). Then, let's take a look at the initializesockets () method and find the following statement:

   If(Unsafenclnativemethods. ossock. wsastartup (Zero X 202,OutLpwsadata)! =Socketerror. Success)
{
Throw NewSocketexception ();
}

You can find that:

  [Dllimport (  "  Ws2_32.dll  "  , Charset  =  Charset. ANSI, setlasterror  =  True  )]
Internal Static Extern Socketerror wsastartup ([in] Short Wversionrequested, Out Wsadata lpwsadata );

ws2_32.dll is the dynamic link library file of the Windows Sockets application interface. You can use this Win32 API in dllimport mode. So when we use the socket class to produce a socket instance, the system will call wsastartup. Every time wsacleanup calls wsastartup, wsacleanup must be called to release resources. If you want to know which protocols are installed in the system and the features of these protocols, you can call int wsaenumprotocols (lpdwprotocols, lpprotocolbuffer, lpdwbufferlength). Generally, you need to call wsaenumprotocols () twice () function to obtain specific protocol information. If you specify lpdwprotocols as null during the first call, the call will certainly fail, but the lpdwbufferlength parameter contains the buffer length required for all protocol information. Now that we know the exact length, we can make the second call. Wsasocket Winsock API is built on the socket, and the socket is actually a handle (we can regard it as an abstract object at the C # level ). Socket wsasocket (int af, int type, int protocols, lpwsaprotocol_info lpprotocolinfo, group G, dowrd dwflags) we can use this function to create a socket

    • AF: Address Family description. If you want to establish a UDP or TCP socket, you can use af_inet to specify the Internet protocol.
    • Type: type description of the new interface. It can be: sockstream, sockdgram, sockseqpacket, sockraw, and sockrdm.
    • Protocol: The specific protocol used by the set interface. If the caller does not want to specify the protocol, the value is set to 0. Note that protocol and type correspond to each other.
    • Lpprotocolinfo: a pointer to the protocol_info structure that defines the features of the created interface. If this parameter is not zero, the first three parameters (AF, type, Protocol) are ignored.
    • G: Set the description of the interface group.
    • Iflags: Set interface property description.

Do you still remember how to call the wsastartup function in. Net C? The innersafeclosesocket class is found in safeclosesocket.

  Internal     Class  Innersafeclosesocket: safehandleminusoneisinvalid
{
// Fields
Private Bool M_blockable;
Private Static Readonly Byte [] Tempbuffer;

// Methods
Static Innersafeclosesocket ();
Protected Innersafeclosesocket ();
Internal Static Safeclosesocket. innersafeclosesocket accept (safeclosesocket sockethandle, Byte [] Socketaddress, Ref Int Socketaddresssize );
[Reliabilitycontract (consistency. willnotcorruptstate, Cer. Success)]
Internal Void Blockingrelease ();
Internal Static Unsafe Safeclosesocket. innersafeclosesocket createwsasocket ( Byte * Pinnedbuffer );
Internal Static Safeclosesocket. innersafeclosesocket createwsasocket (addressfamily, sockettype, protocoltype );
Protected Override Bool Releasehandle ();

// Properties
Public Override Bool Isinvalid {[reliabilitycontract (consistency. willnotcorruptstate, Cer. Success)] Get ;}
}

Let's take a look at how the safeclosesocket. innersafeclosesocket createwsasocket () method is implemented:

  Internal     Static Safeclosesocket. innersafeclosesocket createwsasocket (addressfamily, sockettype, protocoltype)
{
Safeclosesocket. innersafeclosesocket socket = Unsafenclnativemethods. ossock. wsasocket (addressfamily, sockettype, protocoltype, intptr. Zero, 0 , Socketconstructorflags. wsa_flag_overlapped );
If (Socket. isinvalid)
{
Socket. sethandleasinvalid ();
}
Return Socket;
}

You can see the following references in the ossock class:

Code

  [Dllimport (  "  Ws2_32.dll  "  , Charset  =  Charset. Auto, setlasterror  =  True  )]
Internal Static Extern Safeclosesocket. innersafeclosesocket wsasocket ([in] addressfamily, [in] sockettype, [in] protocoltype, [in] intptr protocolinfo, [in] Uint Group, [in] socketconstructorflags flags );



 

But What surprised me was that this ossocket was actually under unsafenclnativemethods. Isn't this safe? There is not much information about unsafenclnativemethods (which of the following experts want to give some advice). I only know what the GC MECHANISM OF. Net means, but not how it is implemented.

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.