Basic Winsock programming and winsock programming

Source: Internet
Author: User

Basic Winsock programming and winsock programming
Basic Winsock programming

The original meaning of Socket is "hole" or "Socket ". As the process Communication Mechanism of bsd unix, take the latter meaning. It is also called "socket". It is used to describe the IP address and port and is a communication chain handle. Hosts on the Internet generally run multiple service software and provide several services at the same time. Each service opens a Socket and binds it to a port. Different ports correspond to different services. Socket is like a porous Socket, just as it was originally intended. A host is like a room with various sockets. Each socket has a serial number. Some sockets provide 220 v ac, some provide 110 v ac, and some provide cable TV programs. The customer software inserts the plug into a socket with different numbers to obtain different services.

1. Based on TCP

It is connection-oriented and stable network communication. Its communication process is as follows:


<1> establish a TCP connection

TCP connection establishment requires three handshakes. The so-called three handshakes are as follows:


  • The client sends a SYN J
  • The server returns a syn k to the client and confirms the syn j. ack j + 1
  • The client sends a confirmation ack k + 1 to the server.

Generally speaking:

A: B. I want to connect to you.

B: A. I see it. connect to it.

A: I have connected.

B: Waiting for acceptance...

<2> TCP connection termination

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


  • An application process first calls close to close the connection, and TCP sends a fin m;
  • After receiving the fin m, the other end performs passive shutdown to confirm the FIN. Its receipt is also passed to the application process as a file Terminator, because the receiving of FIN means that the application process can no longer receive additional data on the corresponding connection;
  • After a period of time, the application process receiving the file Terminator calls close to close its socket. As a result, TCP also sends a fin n;
  • The source sending end TCP that receives the FIN confirms it.

Generally speaking:

A: I want to close it.

B: Do you want to close it?

B: I will close it if I haven't responded for so long.

A: You are about to close it.

B: Disable

<3> TCP stability assurance

It uses the re-transmission confirmation mechanism. If no message is sent, it starts a timer to check whether the message is received by the recipient within a certain period of time. If the message is received, if you do not receive the message, the message will be resent. It is precisely because of this re-transmission mechanism that the efficiency of TCP communication is not higher than that of UDP.

 

2. UDP-based

It is a connectionless and unreliable communication protocol. The communication process is shown in:


3 related functions

<1> WSAStartup Function

IntPASCAL FAR WSAStartup (WORD wVersionRequested, LPWSADATA lpWSAData );

WVersionRequested:Used to specify the version for loading the Winsock database. The low byte represents the master version number, and the high byte represents the minor version number. MAKEWORD (x, y) is usually used to represent the version number. x indicates the high level, and y indicates the low level.

LpWSAData:The returned pointer to the WSADATA struct, which contains information about the major version number.

Return Value:

Success: 0 is returned.

Failed:

WSASYSNOTREADY: indicates that the network device is not ready.

WSAVERNOTSUPPORTTED: the version number of Winsock is not supported.

Wsaeinss SS: A blocked Winsock1.1 exists in the process.

WSAEPROCLIM: it has reached the upper limit of Winsock usage.

WSAEFAULT: lpWSAData is not a valid pointer.

Note:

This function is the initialization function of winsock. If it fails, all related Winsock will not be executed.

<2> socket Functions

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

This socket is a bit similar to a handle or a file pointer.

Af:Address family (address family), which is generally set to AF_INIT, indicating that it is a Socket on the Internet;

Type:Socket type. SOCK_STREAM is used for stream connection and data packet.

SOCK_DGRAM.

Proctocol:Generally, the value is 0, indicating that the default TCP and UDP transmission protocols are used for the two types of sockets.

<3> bind Functions

Int bind (SOCKET s, const sockaddr * name, intnamelen );

This function is used to bind the socket to the specified IP address and port.

S:Socket to be bound

Name: The struct pointer pointing to sockaddr. The struct is as follows:

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

However, the sockaddr_in struct is usually used in Winsock to replace this struct, as shown below:

struct sockaddr_in{short         sin_family;unsigned short        sin_port;struct  in_addr      sin_addr;char         sin_zero[8];};

In_addr is such a struct.

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, And the byte length is 4 bytes. You can use this structure to easily convert the IP address in the dotted-decimal format to the u_long type, and assign the result to S_addr.

Namelen:Length of the struct pointed to by name

Note:

The port number ranges from 0 to 65536, but all the ports at the first point of 1024 are pre-occupied. Therefore, the specified port number must be on it.

In addition, the in_addr and sockaddr struct have the same length of bytes.

<4> listen Function

Int listen (SOCKET s, int backlog );

S:Start the socket of the listener

Backlog:The maximum length of the waiting connection team. Generally, it is set to 1-5.

<5> accept Function

SOCKET accept (SOCKET s, sockaddr * addr, int * addrlen );

S:Socket in the listener status

Addr:Save client information, ip address, port number, etc.

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

Note:

When the accept function is called, the program waits for the client to call the connect function to establish a connection.

<6> connect function

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

S:Connected socket

Addr:Address to connect

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:Socket for sending information

Buf:Buffer for sending/receiving data

Len:Length of message sent/received

Flags: The value that affects function behavior. It is generally set to 0.

Note:

The sending length is generally determined based on the specific length of bytes, and the acceptable length is the length of the entire buffer zone.

<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 Zone

Len: Buffer Length

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

From/to: return value, indicating the peer address information/the peer address information entered

Fromlen/tolen: return value, indicating the length of the Peer address information/the length of the Peer address information entered

<9> closesocket Function

Int closesocket (socket s );

Close a socket.

UDP sample program:

//server#include <WinSock2.h>#include <stdio.h>#pragma comment(lib,"ws2_32.lib") void main(){         WORD wVersionRequested;         WSADATA wsaData;         interr;         wVersionRequested = MAKEWORD(1,1);         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*)&addrClient,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 wVersionRequested;         WSADATA wsaData;         interr;          wVersionRequested = MAKEWORD(1,1);         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*)&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();}


 

 


Basic questions about Winsock programming idiots!

Your server can only do one thing, that is, wait for the client connection and then process it.
You can also take the waiting for client connection as a small task. When there is no client connection, you can do other things to simply understand the server and client, that's what you mean.
Use VC ++ to program and see what you are using. The interface is different from the interface.
 
How to Use the socket class to write winsock Controls

VB network programming-WinSock Control and WinSockAPI

WinSock Introduction
Socket was originally a network communication interface developed by the University of California Berkeley (Berkeley) for UNIX operating systems. With the widespread use of UNIX, socket has become one of the most popular network communication application interfaces. At the beginning of 1990s, several companies, including Sun Microsystems, JSB, FTP software, Microdyne, and Microsoft, jointly customized a set of standards, namely Windows Socket specification (WinSock.

There are two main ways to write network programs in VB: 1. winsock Control 2. winsockAPI

Ii. Use of the WinSock Control
1. Main Properties of the WinSock Control
A. Protocol attributes
You can set the Protocol used by the WinSock Control to connect to a remote computer through the Protocol attribute. The Optional Protocol is the constant of VB corresponding to TCP and UDP: sckTCPProtocol and sckUDPProtocol, respectively. The default protocol of the Winsock Control is TCP. Note: although you can set the Protocol at runtime, the connection must be established or disconnected.

B. SocketHandle attributes
SocketHandle returns the current socket connection handle, which is a read-only attribute.

C. RemoteHostIP attributes
The RemoteHostIP property returns the IP address of the remote computer. On the client side, when the Connect Method of the control is used, the IP address of the remote computer is assigned to the RemoteHostIP attribute. on the server side, after the ConnectRequest event, the remote computer (client) the IP address is assigned to this attribute. If the UDP protocol is used, the IP address of the computer that sends the UDP packet is assigned to this attribute after the DataArrival event.

D. ByteReceived attributes
Returns the number of bytes in the currently received buffer.

E. State attributes
Returns the current status of the WinSock Control.

Constant Value description
SckClosed 0 is disabled by default.
SckOpen 1 is enabled.
SckListening 2 listening
SckConnectionPending 3 connection suspended
SckResolvingHost 4 identifies the host.
SckHostResolved 5 identified host
SckConnecting 6 is connected.
SckConnected 7 is connected.
SckClosing 8 is closing the connection.
SckError 9 Error

2. WinSock main methods
A. Bind Method
The Bind method can be used to fix a port number for this control, so that other applications can no longer use this port.

B. Listen Method
The Listen method is only useful when the TCP protocol is used. It places the application in the monitoring Detection Status.

C. Connect Method
When the local computer and remote computer want to... the remaining full text>

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.