Winsock BASIC Programming

Source: Internet
Author: User
Tags sprintf htons

Winsock BASIC Programming

       Socket " bore " " socket " BSD UNIX process communication IP address generally executes multiple service software, providing several services at the same time. Each service opens a socket and binds to a port, with different ports corresponding to different services. The socket is like a porous socket, as its English intended. A host vac, some provide 110 volts AC, some provide cable TV programs. The customer software plugs into different numbered sockets and can get different services.

1 based on TCP

It is a connection-oriented, stable network communication. Its communication processes such as the following are seen:


<1>TCP Connection Setup

The establishment of a TCP connection requires three handshakes, the so-called three-time handshake, as seen below:


    • Client sends a SYN J to the server
    • The server responds to a SYN K to the client and acknowledges the SYN J ACK j+1
    • Client wants the server to send a confirmation ack k+1

The popular saying is:

A:B, I want to connect you.

B:a, I see, you connect.

A: Well, I can't even

B: Wait for acceptance ...

<2>TCP Connection Termination

The termination of the TCP connection requires the following four waves.


    • An application process first calls close to actively close the connection, when TCP sends a FIN M;
    • Also, after receiving fin m from one end, run the passive shutdown to confirm the fin. Its reception is also passed as a file terminator to the application process, because the receiving of the fin means that the application process can no longer receive additional data on the corresponding connection;
    • After some time, the application process that receives the file terminator calls close to close its socket. This causes its TCP to send also a fin N;
    • This fin is received by the source send side TCP to confirm it.

The popular saying is:

A: I'm going to turn it off.

B: Do you want to close it?

B: It's been a long time, so I'm going to turn it off.

A: I see you're going to turn it off.

B: Off

Guarantee of <3>TCP stability

It is used to confirm the retransmission mechanism, did not send a message it will start a timer, to observe a certain period of time there is no confirmation of the other party, assuming that even if received, confiscated it thought the message did not send over and then will be sent again. It is precisely because of such a confirmation retransmission mechanism that the TCP communication efficiency is not higher than UDP.

2 UDP-based

It is provided for non-connected, unreliable communication protocols. Its communication steps for example with what is seen:


3 Introduction to related functions

<1>wsastartup function

Intpascal far WSAStartup (WORD wversionrequested, Lpwsadata lpwsadata);

wversionrequested: used to specify the version number that is loaded into the Winsock library, the low byte represents the major version number, and the high byte represents the secondary version number. Makeword (x, y) is often used to denote the version number, where X. Represents the high self, and y represents the low byte.

Lpwsadata: Returns a pointer to the WSADATA structure that contains the main information about the version.

return value:

Success: returns 0.

Failed:

Wsasysnotready: Indicates that the network device is not ready.

The Wsavernotsupportted:winsock version number information number is not supported.

Wsaeinprogress: A plug-in Winsock1.1 exists in the process.

Wsaeproclim: The maximum amount of Winsock usage has been reached.

Wsaefault:lpwsadata is not a valid pointer.

Attention:

This function of the Winsock initialization function, assuming that it fails then all the related Winsock behind will not be run.

<2>socket function

Socketsocket (int af, int type, int proctocol);

The socket is a bit like a handle, or a file pointer.

af:address family (addresses family), generally filled with af_init, is a socket on the Internet;

Type: The type of socket, when using the flow connection mode with SOCK_STREAM, using data message mode

Sock_dgram.

Proctocol: typically 0, the default TCP and UDP transport protocol is used for 2 types of sockets respectively.

<3>bind function

int bind (SOCKET s, const sockaddr* name, Intnamelen);

The purpose of this function is to bind the socket to the specified IP address and port.

s: socket to bind

name: The struct pointer to sockaddr*. The structure is seen in the following example:

struct sockaddr{U_shortsa_family;char sa_data[14];};

However, this structure is usually replaced with a sockaddr_in structure in Winsock, as seen in the following:

struct Sockaddr_in{short         sin_family;unsigned short        sin_port;struct  in_addr      sin_addr;char         Sin _ZERO[8];};

IN_ADDR is such a structure

struct IN_ADDR {        union {                struct{UCHAR s_b1,s_b2,s_b3,s_b4;} S_un_b;                struct{USHORT s_w1,s_w2;} S_un_w;                ULONG s_addr;        } S_un;}

We can see that there is a union in this struct with a byte length of 4 bytes. This structure facilitates the conversion of IP addresses in dotted decimal format into u_long types, and results are given to S_ADDR.

Namelen: The length of the struct the name points to

Attention:

The port number has a range of 0-65536, but the port at 10,241 is pre-occupied, so specify the port number above it.

In addition, the byte lengths of the IN_ADDR and sockaddr structures are equal.

<4>listen function

int Listen (SOCKET s, int backlog);

S: start the listening socket

Backlog: The maximum length to wait for a connected team, typically set to 1-5

<5>accept function

Socket accept (socket s, sockaddr* addr, int* Addrlen);

s: socket for listening status

Addr: Save client's information, ip,port number, etc.

Addrlen: The length of the address information, which is also a return value

Attention:

When the Accept function is called, the program waits for the client to call the Connect function for a connection to occur.

<6>connect function

Int Connect (SOCKET s,const sockaddr*name,int namelen);

s: connected sockets

Addr: The address you want to connect to

Addrlen: Length of address information

<7>send/recv function

int Send (SOCKET s,const char* buf,int len,int flags);

int recv (SOCKET s,const char* buf,int len,int flags);

s: send a message to the socket

buf: buffer for sending/receiving data

len: length of message Sent/received

flags: Values that affect the behavior of a function, typically set to 0

Attention:

The length of the send is generally specified by the length of the bytes, and the length of the buffer is the length of the whole.

<8>sendto/recvfrom function

int Recvfrom (SOCKET s, char* buf, int len,int flags, struct sockaddr* from, int* Fromlen);

int Sento (SOCKET s, char* buf, int len, int flags, struct sockaddr* to, int tolen);

S: Your socket

BUF: Buffer

Len: Buffer length

Flags: Typically set to 0, which is a parameter that affects function behavior

From/to: Return value, which indicates the address information of the other person/input address information

Fromlen/tolen: Return value indicating the length of the address information of the other party/the length of the address information entered

<9> closesocket functions

int closesocket (socket s);

Close a socket.

Demo sample program for UDP:

Server#include <WinSock2.h> #include <stdio.h> #pragma comment (lib, "Ws2_32.lib") void Main () {WORD wVe         rsionrequested;         Wsadata Wsadata;         Interr;         wversionrequested = Makeword (a);         Err =wsastartup (Wversionrequested,&wsadata);         if (err!= 0) {return; } if (Lobyte (wsadata.wversion)! = 1 | |                   Hibyte (wsadata.wversion)! = 1) {wsacleanup ();         Return          } Socket SOCKSRV = socket (af_inet,sock_dgram,0);         Sockaddr_in addrsrv; Addrsrv.sin_addr. S_un.         S_addr =htonl (Inaddr_any);         addrsrv.sin_family = af_inet;          Addrsrv.sin_port = htons (6000);         Bind (Socksrv, (sockaddr*) &addrsrv,sizeof (sockaddr));         CHARRECVBUF[100];         CHARSENDBUF[100];          CHARTEMPBUF[200];         Sockaddr_in addrclient;          int len= sizeof (SOCKADDR); while (1) {Recvfrom (SOCKSRV,RECVBuf,100,0, (sockaddr*) &addrclient,&len); if (' q ' = = Recvbuf[0]) {sendto (socksrv, "Q", strlen ("Q") +1,0, (sockaddr*) &ad                            Drclient,len);                   printf ("chat end");                   } sprintf (Tempbuf, "%s say:%s", Inet_ntoa (ADDRCLIENT.SIN_ADDR), recvbuf);                    printf ("%s\n", tempbuf);                   printf ("Please input data:\n");                   Gets (SENDBUF);         SendTo (Socksrv,sendbuf,strlen (SENDBUF) +1,0, (sockaddr*) &addrclient,len);         } closesocket (SOCKSRV); WSACleanup ();}


Client#include <WinSock2.h> #include <stdio.h> #pragma comment (lib, "Ws2_32.lib") void Main () {WORD wVe         rsionrequested;         Wsadata Wsadata;          Interr;         wversionrequested = Makeword (a);         Err =wsastartup (Wversionrequested,&wsadata);                   if (err!= 0) {printf ("WSAStartup failed\n");         Return } if (Lobyte (wsadata.wversion)! = 1 | |                   Hibyte (wsadata.wversion)! = 1) {wsacleanup ();         Return                 } SOCKET sockclient =socket (af_inet,sock_dgram,0);         Sockaddr_in Addrserver; Addrserver.sin_addr. S_un.         S_addr =inet_addr ("127.0.0.1");         addrserver.sin_family = af_inet;          Addrserver.sin_port = htons (6000);         CHARRECVBUF[100];         CHARSENDBUF[100];         CHARTEMPBUF[200];          int len= sizeof (SOCKADDR);                while (1) {printf ("Please input data\n");   Gets (SENDBUF);                   SendTo (Sockclient,sendbuf,strlen (SENDBUF) +1,0, (sockaddr*) &addrserver,len);                   Recvfrom (sockclient,recvbuf,100,0, (sockaddr*) &addrserver,&len); if (' q ' = = Recvbuf[0]) {sendto (sockclient, "Q", strlen ("Q") +1,0, (sockaddr*) &amp                            ; addrserver,len);                            printf ("chat end\n");                   Break                   } sprintf (Tempbuf, "%s say:%s", Inet_ntoa (ADDRSERVER.SIN_ADDR), recvbuf);          printf ("%s\n", tempbuf);         } closesocket (Sockclient); WSACleanup ();}


Winsock BASIC Programming

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.