Chapter 2 Introduction to Winsock

Source: Internet
Author: User
Tags htons

Microsoft Windows Network Programming 2nd Edition translated by Yang Heqing Tsinghua University Press

Network Programming for Microsoft Windows 2nd

1. Winsock is a network interface, not a protocol.

2 Winsock has two versions: 1 and 2, which can be distinguished by the function prefix WSA.

WSA prefix before the number. However, there are several exceptions: wsastartup, wsacleanup, wsarecvex,

Wsagetlasterror is a 1.1 Standard.

3. wince only supports winsock1

Winsock1 Winsock. h wsock32.lib

Winsock2 winsock2.h ws2_32.lib

Programming extension mswsock. h mswsock. dll

4. Use wsastartup for Winsock initialization. For more information, see msdn and books.

At the end, use wsacleanup to release resources allocated by Winsock, or enable the operating system to automatically

Released, but this does not comply with the Winsock specification.

5 sockaddr_in is used to specify the IP address and port number

Struct sockaddr_in {

Short sin_family; // The value must be af_inet.

Unsigned short sin_port; // port number

Struct in_addr sin_addr; // ip address, which can be obtained by inet_add (char *)

Char sin_zero [8]; // fill to make it the same length as the sockaddr Structure

};

6 on the inter86 processor, multi-byte is a small-Endian, Internet standard word

The big-Endian mode is called network-byte ).

Host-byte-to-Network-byte Function

Htonl, wsahtonl, htons, wsahtons

Network-byte to host-byte

Ntohl, wsantohl, ntohs, wsantohs

7. Create a socket function

Socket and wsasocket. After the socket is created, use the following function to control socket options and sockets

Behavior: setsockopt, getsockopt, ioctlsocket, and wsaioctl

The following is an example of a TCP server program.

// Module name: tcpserver. CPP //// Description: This example demonstrates how to develop a simple TCP server application. // This application listens to TCP connections and receives data on port 5150. This // example is implemented in the form of a console. When a connection is accepted or data is received, // simply print the information on the console. //// Note: Set the ws2_32.lib library, project --> Settings --> connection, and add // ws2_32.lib to the end of "Object/Library module. # Include <winsock2.h> # include <stdio. h> void main (void) {// initialize WinSock and use int ret of Version 2.2; wsadata; If (ret = wsastartup (makeword (2, 2), & wsadata )! = 0) {// Note: wsastartup fails to load. We cannot use wsagetlasterror // as usual to get the error code, but we can judge that printf ("wsastartup failed based on the returned status, error code % d \ n ", RET); return;} // create socketsocket listeningsocket; If (listeningsocket = socket (af_inet, sock_stream, ipproto_tcp) = invalid_socket) {printf ("failed to create socket, error code % d \ n", wsagetlasterror (); wsacleanup (); Return ;}// set the addr_in struct, note that the port number must be converted to sockaddr_in serveraddr; int Port = 5150; serveraddr. sin _ Family = af_inet; serveraddr. sin_port = htons (port); serveraddr. sin_addr.s_addr = htonl (inaddr_any); // bind the address information to the socket If (BIND (listeningsocket, (sockaddr *) & serveraddr, sizeof (serveraddr) = socket_error) {printf ("binding failed, error code % d \ n", wsagetlasterror (); closesocket (listeningsocket); wsacleanup (); Return ;}// listen to client connection, the queue length is 5if (Listen (listeningsocket, 5) = socket_error) {printf ("listening failed, error code % d \ n", wsagetlaste Rror (); closesocket (listeningsocket); wsacleanup (); return;} printf ("waiting for connection on port % d. \ N ", Port); sockaddr_in clientaddr; int clientaddrlen = sizeof (clientaddr); socket newconnection; If (newconnection = accept (listeningsocket, (sockaddr *) & clientaddr, & clientaddrlen) = invalid_socket) {printf ("failed to accept connection, error code % d \ n", wsagetlasterror (); closesocket (listeningsocket); wsacleanup (); return;} printf ("received a connection from % s: % d. \ N ", inet_ntoa (clientaddr. sin_addr), ntohs (clientaddr. sin_port); // there are two options: Use listeningsocket to continue the accept client connection and // send and receive data. The other is to disable listeningsocket and no longer receive client connections. Here we select // no longer receive client connections, but simply send and receive data closesocket (listeningsocket) with the newly established connection newconnection; // use newconnection to send and receive data, for simplicity, we only accept some data and report the length of the received char databuffer [1024]; printf ("waiting to receive data... \ n "); If (ret = Recv (newconnection, databuffer, sizeof (databuffer), 0) = socket_error) {printf (" failed to receive data, error code % d \ n ", wsagetlasterror (); closesocket (newconnection); wsacleanup (); return;} printf (" successfully received % d byte data \ n ", RET); // do not do anything, so close the client connection printf ("close client connection \ n"); closesocket (newconnection ); // after the program finishes processing the connection, it calls wsacleanupwsacleanup ();}

The following is an example of a tcp client program.

// Module name: tcpclient. CPP //// Description: This example demonstrates how to develop a simple tcp client application, // This program simply sends a // "hello" message to the server listening port 5150. This example is implemented in the form of a console. When the connection is successful // or data is sent to the server, the information is simply printed on the console. //// Note: Set the ws2_32.lib library, project --> Settings --> connection, and add // ws2_32.lib to the end of "Object/Library module. # Include <winsock2.h> # include <stdio. h> void main (INT argc, char ** argv) {// the IP address must be used as the command line parameter if (argc <= 1) {printf ("Usage: tcpclient <Server IP address>. \ N "); return;} // initialize WinSock, use int ret of Version 2.2; wsadata; If (ret = wsastartup (makeword (2, 2), & wsadata )! = 0) {// Note: wsastartup fails to load. We cannot use wsagetlasterror // as usual to get the error code, but we can judge that printf ("wsastartup failed based on the returned status, error code % d \ n ", RET); return;} // create socketsocket s; If (S = socket (af_inet, sock_stream, ipproto_tcp) = invalid_socket) {printf ("failed to create socket, error code % d \ n", wsagetlasterror (); wsacleanup (); Return ;}// set the addr_in struct, note that the port number must be converted to sockaddr_in serveraddr; int Port = 5150; serveraddr. sin_family = af_inet; serveraddr. Sin_port = htons (port); serveraddr. sin_addr.s_addr = inet_addr (argv [1]); printf ("Connecting % s: % d... \ n ", inet_ntoa (serveraddr. sin_addr), ntohs (serveraddr. sin_port); If (connect (S, (sockaddr *) & serveraddr, sizeof (serveraddr) = socket_error) {printf ("unable to connect, error code % d \ n ", wsagetlasterror (); closesocket (s); wsacleanup (); return;} printf (" connection successful. \ N "); printf (" try to send "hello" message \ n "); If (ret = Send (S," hello ", 5, 0 )) = socket_error) {printf ("failed to send, error code % d \ n", wsagetlasterror (); closesocket (s); wsacleanup (); return ;} printf ("successfully sent % d byte data \ n", RET); // do not do anything, so disable Client Connection printf ("close connection \ n "); closesocket (s); // after the program finishes processing the connection, it calls wsacleanupwsacleanup ();}

UDP acceptor example

// Module name: udpreceiver. cpp /// Description: This example demonstrates how to develop a simple UDP receiving program, // It waits for packets on port 5150. The example is implemented in the form of // on the console. when data is received, the information is simply printed on the control // platform. //// Note: Set the ws2_32.lib library, project --> Settings --> connection, and add // ws2_32.lib to the end of "Object/Library module. # Include <winsock2.h> # include <stdio. h> void main (INT argc, char ** argv) {// initialize WinSock, use int ret of Version 2.2; wsadata; If (ret = wsastartup (makeword (2, 2), & wsadata )! = 0) {// Note: wsastartup fails to load. We cannot use wsagetlasterror // as usual to get the error code, but we can judge that printf ("wsastartup failed based on the returned status, error code % d \ n ", RET); return;} // create socketsocket receivingsocket; If (receivingsocket = socket (af_inet, sock_dgram, ipproto_udp) = invalid_socket) {printf ("failed to create socket, error code % d \ n", wsagetlasterror (); wsacleanup (); Return ;}// set sockaddr_in receiveraddr; int Port = 5150; receiveraddr. sin_family = af_ I Net; receiveraddr. sin_port = htons (port); receiveraddr. sin_addr.s_addr = htonl (inaddr_any); // bind the address information to the socket If (BIND (receivingsocket, (sockaddr *) & receiveraddr, sizeof (receiveraddr) = socket_error) {printf ("binding failed, error code % d \ n", wsagetlasterror (); closesocket (receivingsocket); wsacleanup (); return ;} printf ("waiting for receiving packets on port % d. \ N ", Port); char receivebuf [1024]; int buflength = 1024; sockaddr_in senderaddr; int senderaddrsize = sizeof (senderaddr); If (ret = recvfrom (mongoingsocket, callback, callback, buflength, 0, (sockaddr *) & senderaddr, & senderaddrsize) = invalid_socket) {printf ("recvfrom failure, error code % d \ n", wsagetlasterror ()); closesocket (receivingsocket); wsacleanup (); return;} printf ("receive % d byte data from % s: % d \ n", inet_ntoa (senderaddr. sin_addr), ntohs (senderaddr. sin_port), RET); closesocket (receivingsocket); // call wsacleanupwsacleanup () after the program finishes processing the connection ();}

UDP sending end example

// Module name: udpsender. CPP //// Description: This example demonstrates how to develop a simple UDP sender program, which will send a "hello" message to the receiving end port 5150. // The example is implemented in the console. when the information is sent to the server, // simply print the information on the console. //// Note: Set the ws2_32.lib library, project --> Settings --> connection, and add // ws2_32.lib to the end of "Object/Library module. # Include <winsock2.h> # include <stdio. h> void main (INT argc, char ** argv) {// the IP address must be used as the command line parameter if (argc <= 1) {printf ("Usage: udpsender <acceptor IP address>. \ N "); return;} // initialize WinSock, use int ret of Version 2.2; wsadata; If (ret = wsastartup (makeword (2, 2), & wsadata )! = 0) {// Note: wsastartup fails to load. We cannot use wsagetlasterror // as usual to get the error code, but we can judge that printf ("wsastartup failed based on the returned status, error code % d \ n ", RET); return;} // create socketsocket sendingsocket; If (sendingsocket = socket (af_inet, sock_dgram, ipproto_udp) = invalid_socket) {printf ("failed to create socket, error code % d \ n", wsagetlasterror (); wsacleanup (); Return ;}// set sockaddr_in receiveraddr; int Port = 5150; receiveraddr. sin_family = af_inet; receiveraddr. sin_port = htons (port); receiveraddr. sin_addr.s_addr = inet_addr (argv [1]); // send the packet if (ret = sendto (sendingsocket, "hello", 5, 0, (sockaddr *) & receiveraddr, sizeof (receiveraddr) = socket_error) {printf ("failed to send, error code % d \ n", wsagetlasterror (); closesocket (sendingsocket); wsacleanup (); return;} printf ("% d byte data \ n", inet_ntoa (receiveraddr. sin_addr), ntohs (receiveraddr. sin_port), RET); // after data is sent, close the connection to closesocket (sendingsocket); // after the program finishes processing the connection, it calls wsacleanupwsacleanup ();}

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.