Windows Sockets Network Programming Basics

Source: Internet
Author: User
Tags set socket htons

The following describes the implementation of the Network 7 layer protocol in Windows:

7-Layer Protocol win system
________________________________________
7 Application Tier 7 applications
________________________________________________
6 Presentation layer 6 WINSOCK API (DLL)
___________________________________________
5 Session Layer 5 SPI (DLL)
__________________________________________________
4 Transport Layer 4 TDI (Vxd,sys)
___________________________________________________
3 Network Layer 3 NDIS (Vxd,sys)
__________________________________________________
2 Data Link Layer 2 NIC driver (Vxd,sys)
___________________________________________
1 Physical Layer 1 network connection
_________________________________________________
I believe this map will give you a better understanding of their correspondence.


TCP protocol Diagram

Application Protocol HTTP FTP TELNET
Transport protocol TCP UDP
Internet Protocol IP
Physical layer protocol NIC

The IP protocol guarantees the transmission of data, and the TCP protocol guarantees the quality of transmission.
TCP/IP protocol is based on four layer structure: the application layer, the transport layer, the network layer, the interface layer, the data in the transmission each through the first layer will be in the data, the data for the receiving end of the same level of use, in
At the receiving end, each layer of the head is removed to ensure consistent transmission data format.


TCP Header structure:
16-bit Source port number 16-bit destination port number
_______________________________________________________________________________
32-bit serial number
___________________________________________________________________________
32 Digit Confirmation Number
_____________________________________________________________________________________
4-Bit header length + 6-bit reserved word 6-bit flag 16-bit window size
_______________________________________________________________________________________
16-bit checksum and 16-bit emergency data offset
_____________________________________________________________________________________
Data segment
_______________________________________________________________________________


IP Header structure:
4-bit IP version number 4-bit header length 8-bit service type 16-bit total length
___________________________________________________________________________________________
16-bit indication 3-bit flag and offset
__________________________________________________________________________
8-bit time-to-Live 8-bit protocol 16-bit IP header checksum
_________________________________________________________________________________________
32-bit Source IP address
___________________________________________________________________________________________
32-bit Destination IP address
________________________________________________________________________________________
TCP Headers and data

____________________________________________________________________________
Section fourth about server and client programming


In network programming, the most common and most basic is Winsock. Now let's talk about socket programming under Windows.

All of the Winsock programming on the WIN32 platform takes the following steps:
Define variables---Get Windock version, load Winsock Library, create sockets, set socket options, close sockets > Uninstall Winsock Library, releasing resources

The process of establishing Winsock C/s is described below:

Server Client
________________________________________________
1 Initialize WSA 1 initialize WSA
____________________________________________________
2 Set up a socket 2 to create a socket
_____________________________________________________
3 binding Socket 3 connecting to the server
_____________________________________________________
4 listening on the specified port 4 sending and receiving data
_____________________________________________________
5 Accept a Connection 5 disconnect
______________________________________________________-
6 Sending and receiving data
___________________________________________________
7 disconnecting
__________________________________________________

It is noted that in the VC for WINSOCK programming, the following two library files need to be introduced: Winsock. H (This is the Winsock API header file, Win2K above support WINSOCK2, so
can be used WINSOCK2.H); Ws2_32.lib (WINSOCK API connection library file).
Use the following methods:
#include
#pragma comment (lib, "Ws2_32.lib")

It is noted that in the VC for WINSOCK programming, the following two library files need to be introduced: Winsock. H (This is the Winsock API header file, Win2K above support WINSOCK2, so
can be used WINSOCK2.H); Ws2_32.lib (WINSOCK API connection library file).
Use the following methods:
#include
#pragma comment (lib, "Ws2_32.lib")

Below we demonstrate the workflow of the server and client through specific code:

First, build a wsadata structure, usually with wsadata
Wsadata Wsadata;

Then, call the WSAStartup function, which is the first call to connect the application with Winsock.dll. Where the first parameter is the Winsock version number, and the second parameter is a pointer to the
Wsadata pointer. The function returns an int value that is checked to determine whether the initialization was successful. The invocation format is as follows: WSAStartup (Makeword (2,2), &wsadata), where
Makeword (2,2) indicates the use of the WINSOCK2 version. Wsadata is used to store the data that the system returns about Winsock.

if (Iresuit=wsastartup (Makeword (2,2), &wsadata)!=0)
{
printf ("WSAStartup failed:%d", GetLastError ()); The return value is unequal to 0, indicating that initialization failed
ExitProcess (); Exit program
}

After the application finishes using the requested socket library, call the WSACleanup function to contact the socket library's bindings and release the resources.

Note After initialization of WSAStartup, a socket structure must be established to hold the socket handle.

Below we create a socket.

First we create a m_socket socket handle, then call the socket () function, and the function return value is saved in M_socket. We use AF_INFE,SOCK_STREAM,IPPROTO_TCP
Three parameters. The first represents the address family, AF_INFE represents the TCP/IP family, the second represents the service type, and in WINSOCK2, the socket supports the following three types;

Sock_stream Streaming sockets
Sock_dgram datagram sockets
Sock_raw RAW sockets

The third parameter represents a protocol:

IPPROTO_UDP UDP protocol for non-connected datagram sockets
IPPROTO_TCP TCP protocol for streaming sockets
IPPROTO_ICMP ICMP protocol for RAW sockets

M_socket=socket (AF_INFE,SOCK_STREAM,IPPROTO_TCP); Create a TCP protocol

The following code is used to check the return value for errors:

if (M_scoket==invalid_socket)
{
PRINRF ("Error at Socket ():%d\n", GetLastError ());
WSACleanup (); Freeing resources
Return
}
Description, if the SOCKET () call fails, he will return Invalid_socket.


In order for the server to accept a connection, he must bind a network address, the following code shows how to bind an already initialized IP and port socket. Client program with this
IP address and port to connect to the server.

SOCKADDR_IN Service;
Service.sin_family=af_inet; Internet address Family
SERVICE.SIN_ADDR.S_ADDR=INET_ADDR ("127.0.0.1"); The local IP address that will be bound
Service.sin_port=htons (27015); 27015 ports that will be bound


Let's call the BIND function, pass the socket and sockaddr as arguments, and check for errors.

if (Bind (M_socket, (sockaddr*) &service,sizeof (SERVICE)) ==socket_error)
{
printf ("Bind () failed.\n");
Closesocket (M_socket);
Return
}

When the binding is complete, the server must establish a listening queue to accept requests from the client. Listen () causes the server to enter a listening state, the function call successfully returns 0, otherwise returns
Socket_error. Code is as follows:

if (Listen (m_socket,1) ==socket-error)
{
printf ("Error listening on socket.\n");
}

If the client calls the Connect () function at this point after the server has finished calling listen (), the server side must call accept (). So that the server and the client are formally completing the communication program.
Connection action.

Once the server is listening, we will specify a handle to represent the connection accepted using the Accept () function, which is the representation used to send and receive data. Create a socket handle
The Socket AcceptSocket then uses an infinite loop to detect if there is a connection coming in. Once there is a connection request, the ACCEPT () function is called and returns the handle to the connection.

printf ("Waitong for a client to connect...\n");
while (1)
{
Acceptsocket=socket_error;
while (Acceptsocket==socket_error)
{
Acceptsocket=accept (M_socket,null,null);
}
}


Here's a look at the client side code:

Sockaddr_in ClientService;
Clientservice.sin_family=af_inet; Internet address Family
CLIENTSERVICE.SIN_ADDR.S_ADDR=INET_ADDR ("127.0.0.1"); The local IP address that will be bound
Clientservice.sin_port=htons (27015); 27015 ports that will be bound

Call the Connect () function below:

if (Connect (M_socket, (sockaddr*) &clientservice, sizeof (clientservice)) = = Socket_error)
{
printf ("Failed to connect.\n");
WSACleanup ();
Return
}//If the call fails cleanup exits
The call continues to read and write data successfully

_____________________________________________________________________________________
Here, the basic process of server and client is introduced, the following we introduce the data exchange.


Send ():
int send
{
Socket s,//Specify Send End Sockets
const char FAR?*BUF,//indicates a buffer that holds the data to be sent by the application
int len,//number of data bytes actually to be sent
int flags//general set to 0
};
C/S uses the Send function to send data to the other end of the TCP connection.

Recv ():
int recv
{
Socket s,//Specify Send End Sockets
Char Far?*buf,//indicates that a buffer holds the data RECC received
int Len,//indicates the length of the BUF
int flags//general set to 0

};
C/S uses the RECV function to accept data from the other end of the TCP connection

_______________________________________________________________________________________________


The following is the complete program code provided below, you can directly compile and run


First look at the client's code:

#include <winsock2.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
void Main () {

Initializes the Winsock.
Wsadata Wsadata;
int iresult = WSAStartup (Makeword (2,2), &wsadata);
if (iresult! = no_error)
printf ("Error at WSAStartup () \ n");

Create a socket socket.
SOCKET client;
Client = socket (af_inet, sock_stream, ipproto_tcp);

if (client = = Invalid_socket) {
printf ("Error at Socket ():%ld\n", WSAGetLastError ());
WSACleanup ();
Return
}

Connect to the server.
Sockaddr_in ClientService;

clientservice.sin_family = af_inet;
CLIENTSERVICE.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");
Clientservice.sin_port = htons (27015);

if (Connect (client, (sockaddr*) &clientservice, sizeof (clientservice)) = = Socket_error) {
printf ("Failed to connect.\n");
WSACleanup ();
Return
}

Send and receive data.
int bytessent;
int bytesrecv = Socket_error;
Char sendbuf[32] = "client:sending data.";
Char recvbuf[32] = "";

BytesSent = Send (client, SendBuf, strlen (SENDBUF), 0);
printf ("Bytes Sent:%ld\n", bytessent);

while (bytesrecv = = Socket_error) {
BYTESRECV = recv (client, Recvbuf, 32, 0);
if (Bytesrecv = = 0 | | bytesrecv = = wsaeconnreset) {
printf ("Connection closed.\n");
Break
}
if (Bytesrecv < 0)
Return
printf ("Bytes Recv:%ld\n", BYTESRECV);
}

Return
}


Here is the server-side code:

#include <winsock2.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
void Main () {

Initialization
Wsadata Wsadata;
int iresult = WSAStartup (Makeword (2,2), &wsadata);
if (iresult! = no_error)
printf ("Error at WSAStartup () \ n");

Creating sockets
SOCKET server;
Server = socket (af_inet, sock_stream, ipproto_tcp);

if (server = = Invalid_socket) {
printf ("Error at Socket ():%ld\n", WSAGetLastError ());
WSACleanup ();
Return
}

Bind socket
SOCKADDR_IN Service;

service.sin_family = af_inet;
SERVICE.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");
Service.sin_port = htons (27015);

if (Bind (server, (sockaddr*) &service, sizeof (service)) = = Socket_error) {
printf ("Bind () failed.\n");
Closesocket (server);
Return
}

Monitor socket
if (Listen (server, 1) = = Socket_error)
printf ("Error listening on socket.\n");

Accept Connection
SOCKET AcceptSocket;

printf ("Waiting for a client to connect...\n");
while (1) {
AcceptSocket = Socket_error;
while (AcceptSocket = = Socket_error) {
AcceptSocket = Accept (server, NULL, NULL);
}
printf ("Client connected.\n");
Server = AcceptSocket;
Break
}

Send acceptance data
int bytessent;
int bytesrecv = Socket_error;
Char sendbuf[32] = "server:sending Data.";
Char recvbuf[32] = "";

BYTESRECV = recv (server, Recvbuf, 32, 0);
printf ("Bytes Recv:%ld\n", BYTESRECV);

BytesSent = Send (server, SendBuf, strlen (SENDBUF), 0);
printf ("Bytes Sent:%ld\n", bytessent);

Return
}
This procedure only describes the situation of synchronization!

The fifth section introduces the multithreading programming

For the basic concept of multithreading, I am not repeating that, as long as the learning of a programming language should be more processes and threads have a basic understanding. Here are some highlights on how to implement multithreading.

Usually the main thread of a program has an operating system created, and if you want it to create additional threads, you can call the CreateThread () function to complete it. The original function is as follows:

HANDLE CreateThread ()
{
Lpsecurity_attributes lpthreadattributes,//Pointer to Security_attributes
size_t dwstacksize,//Indicates the size of the address space allocated by the thread for its own stack system default value is 0
Lpthread_start-toutine lpstartaddress,//Indicates the address of the function that the code is in when the new thread starts executing, that is, the name of the thread
LPVOID Lpparameter,//is the parameter of the incoming thread function
DWORD dwCreationFlags,//Specifies additional flags created by the control thread take 0 threads to execute immediately take create_suspended thread hangs
Lpdword LPTHREADLD//is a DWORD-type address that returns the ID assigned to the new thread
}

The thread function Lpparameter must have the following prototype:

DWORD WINAPI Xxxthreadfun (LPVOID lpparameter)
{
return (0);
}

________________________________________________________________________________________
Let's create a thread:

#include
#include
DWORD WINAPI ThreadFunc (LPVOID lpparam)//thread function, no different than normal function
{
printf ("Parameter =%d.", * (dword*) lpparam);
return 0;
}

void Main (void)
{
DWORD dwThreadID, Dwthrdparam = 1;
HANDLE Hthread;
Hthread = CreateThread (Null,0,threadfunc,&dwthrdparam, 0,&dwthreadid);
if (hthread = = NULL)
{
printf ("CreateThread failed (%d) \ n", GetLastError ());
}
Else
{
_getch ();
CloseHandle (Hthread);
}
}

On the thread synchronization problem, here is no longer explained, please consult their own information, do not check the future may be difficult ah. Cultivate your own hands-on ability.

Windows Sockets Network Programming Basics

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.