Windows socket programming

Source: Internet
Author: User
Tags htons

 

Applications that use the TCP/IP protocol usually use two application programming interfaces (APIS): socket and TLI (Transport Layer ). The former is sometimes called "Berkeley socket", indicating that it has evolved from the Berkeley edition. The latter was initially developed by AT & T, sometimes referred to as xTi (x/open transport layer interface), to acknowledge the work done by X/open, an international computer manufacturer with its own defined standards. XTi is actually a superset of TLI. In Windows, the socketapi for Windows is implemented, also known as Winsock. We all know that both TCP/IP and osi iso protocols are in hierarchical mode. You only need to complete the features of the Self-layer by shielding the details of the lower layer using the layer concept, therefore, programmers do not need to care about the specific implementation of the network underlying layer when programming on the network. They only need to care about the functions of the software to greatly simplify programming. Therefore, when learning network socket programming, we do not need a lot of network knowledge, or even the knowledge of TCP/IP protocol. As a result, I will not introduce that knowledge. If you want to know about the classic introduction that has been applied N times on the internet.
This section only describes the simple programming implementation based on TCP and UDP. Today's network programs are generally based on the C/S model, that is, the client-server model. This structure places the main operation operations on the central computer. Compared with centralized large-scale computing systems, the main advantages of the "customer-server" Structure
It provides good practicability, flexibility, interactivity and scalability. "Customer-server" replaces centralized file sharing with database servers to achieve loose coupling between computer systems.
"Client/Server" is a typical web information system model. The term "customer-server" was first proposed in 1980s. Initially, it mainly refers to the connection between personal computers and web, it mainly refers to the information exchange transmission mode between computer systems through web; "customer" refers to the requester of information services, and "server" refers to the provider of services,
Depending on the software settings, a computer can be either a customer or a server. With the development of web technology, the "customer-server" software framework has become a flexible, distributed, and modular information system structure. Windows Sockets is Microsoft
Windows network programming interface, which is extended from Berkeley sockets and provided to us as a dynamic link library. Windows
On the basis of inheriting the main features of Berkeley sockets, sockets has extended significantly. These extensions mainly provide some asynchronous functions and support asynchronous selection of network events that comply with the Windows message driver features. Windows Sockets
Both 1.1 and Berkeley sockets are based on the TCP/IP protocol.
Sockets 1.1 has developed and is not protocol-independent and backward compatible. It can be used at any bottom.
The communication capability provided by the layer transport protocol is used to complete network data communication for upper-layer applications, regardless of the Communication Status of the underlying network link. This truly makes the underlying network communication transparent to applications. There are three types of sockets: 1)
Streaming socket (sock_stream) provides connection-oriented and reliable data transmission services. Data is sent without errors or duplicates and is received in the sending order. This type is based on the TCP protocol. 2)

The datagram socket (sock_dgram) provides the connectionless service. Data packets are sent in the form of independent packets without error guarantee. data may be lost or duplicated, and the receiving order is disordered.
This type is based on UDP protocol 3)
Original socket (sock_raw ). It is used to compile a program based on the IP protocol.
It can access protocol packages such as ICMP and ICMP, write IP data packets not processed by the kernel, and create custom IP data packet headers. Based on
TCP (
Connection-oriented
)
Of
Socket
Programming process:
Server programs: 1. Create a socket ). 2. Bind the socket to a local address and port (BIND ). 3. Set the socket to the listening mode and prepare to receive the client request (Listen ). 4. Wait for the customer's request to arrive. When the request arrives, accept the connection request and return a new socket (accept) corresponding to the connection ). 5. Use the returned socket to communicate with the client (send/Recv ). 6. Return and wait for another customer's request. 7. Close the socket. Program code: // 1. Create Socket socket socksrv =
Socket (af_inet, sock_stream, ipproto_tcp); If (invalid_socket =
Wsagetlasterror () MessageBox (null,
"Create socket failed! "," Error ", mb_ OK); // 2. Bind the socket to a port number sockaddr_in addrsrv; memset (& addrsrv, 0,
Sizeof (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); // 3. Set the socket to the listening mode listen (socksrv,/* somaxconn */
5); // 4. Wait for the user's connection to arrive. sockaddr_in addrclient; int socklen =
Sizeof (sockaddr); While (1) {socket sockconn =
Accept (socksrv, (sockaddr *) & addrclient, & socklen); If (invalid_socket =
Wsagetlasterror ())
MessageBox (null, "Connect client failed! "," Error ", mb_ OK); // 5. Use the returned socket to communicate with the user, send data, or accept data char sendbuf [100]; wsprintf (sendbuf,
"Welcome % s to my computer ",
Inet_ntoa (addrclient. sin_addr); send (sockconn,
Sendbuf, sizeof (sendbuf) + 1, 0); If (socket_error =
Wsagetlasterror ())
MessageBox (null, "server send data failed! "," Error ", mb_ OK); char recvbuf [100]; Recv (sockconn,
Recvbuf, 100, 0); If (socket_error =
Wsagetlasterror ())
MessageBox (null, "server recieve data failed! "," Error ", mb_ OK); printf (" % s/n ",
Recvbuf); // 6. Close the requested socket resource closesocket (sockconn);} client program: 1. Create a socket ). 2. Send a connection request to the server ). 3. Send/Recv ). 4. Close the socket. Program code: // 1. Create Socket socket sockclient =
Socket (af_inet, sock_stream, ipproto_tcp); If (invalid_socket =
Wsagetlasterror () MessageBox (null,
"Create socket failed! "," Error ", mb_ OK); // 2. Send the connection request sockaddr_in addrsrv to the server; addrsrv. sin_addr.s_un.s_addr =
Inet_addr ("127.0.0.1"); addrsrv. sin_family = af_inet; addrsrv. sin_port =
Htons (6000); Connect (sockclient,
(Sockaddr *) & addrsrv, sizeof (sockaddr); // 3. Communicate with the server to receive or send data char recvbuf [100]; Recv (sockclient, recvbuf,
100, 0); If (socket_error =
Wsagetlasterror ())
MessageBox (null, "server recieve data failed! "," Error ", mb_ OK); printf (" % s/n ", recvbuf); char sendbuf [] =" Hello
Server "; send (sockclient, sendbuf,
Sizeof (sendbuf) + 1, 0); If (socket_error =
Wsagetlasterror ())
MessageBox (null, "server send data failed! "," Error ", mb_ OK); // 4. Disable socket resources and uninstall the socket dynamic link library closesocket (sockclient); wsacleanup (); Based on
UDP (
Connection-free
)
Of
Socket
Programming
Server (receiving end) Program: 1. Create a socket ). 2. Bind the socket to a local address and port (BIND ). 3. Waiting for receiving data (recvfrom ). 4. Close the socket. Program code: // 1. Create Socket socket socksrv =
Socket (af_inet, sock_dgram, ipproto_udp); If (invalid_socket =
Wsagetlasterror () MessageBox (null,
"Create socket failed! "," Error ", mb_ OK); // 2. Bind the socket to the specified port sockaddr_in addrsrv; addrsrv. sin_addr.s_un.s_addr =
Htonl (inaddr_any); addrsrv. sin_family = af_inet; addrsrv. sin_port =
Htons (5000); BIND (socksrv,
(Sockaddr *) & addrsrv, sizeof (sockaddr); If (socket_error =
Wsagetlasterror () MessageBox (null, "Bind
Fuction failed! "," Error ", mb_ OK); // 3. Char recvbuf [100]; sockaddr_in addrclient; int fromlen = 100; recvfrom (socksrv, recvbuf,
100, 0, (sockaddr *) & addrclient, & fromlen); If (socket_error =
Wsagetlasterror () MessageBox (null,
"Recvfrom fuction failed! "," Error ", mb_ OK); printf (" % s/n ", recvbuf); // 4. close socket closesocket (socksrv); wsacleanup (); client (sending end) Program: 1. Create socket ). 2. Send data (sendto) to the server ). 3. Close the socket. Program code: // 1. Create Socket socket sockclient =
Socket (af_inet, sock_dgram, ipproto_udp); If (invalid_socket =
Wsagetlasterror () MessageBox (null,
"Create socket failed! "," Error ", mb_ OK); // 2. send data to the server char sendbuf [100] =" UDP
Server, good evening! "; Sockaddr_in addrsrv; addrsrv. sin_addr.s_un.s_addr =
Inet_addr ("127.0.0.1"); addrsrv. sin_family = af_inet; addrsrv. sin_port =
Htons (5000); int tolen = 100; sendto (sockclient, sendbuf,
Sizeof (sendbuf) + 1, 0, (sockaddr *) & addrsrv, tolen); // 3. Disable socket closesocket (sockclient); wsacleanup ();
Related Article

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.