Transferred from: http://www.cnblogs.com/huxc/p/4272940.html
Service side:
#define _crt_secure_no_warnings#include <stdio.h> #include <winsock2.h> #pragma comment (lib, "Ws2_32.lib" )/*tcp server */int main (void) {int len = 0; Wsadata wd;int ret = 0; SOCKET s, c;char sendbuf[1000] = "", recvbuf[1000] = ""; Sockaddr_in saddr, Caddr;ret = WSAStartup (Makeword (2, 2), &WD); /*1. Initialization operation */if (ret! = 0) {return 0;} if (Hibyte (wd.wversion)! = 2 | | Lobyte (wd.wversion)! = 2) {printf ("Initialization failed"); WSACleanup (); return 1;} /*2. Create server-side SOCKET*/S = socket (af_inet, sock_stream, 0);/*3. Set the server-side information */saddr.sin_addr. S_un. S_ADDR = htonl (inaddr_any); saddr.sin_family = af_inet; /* protocol Type */saddr.sin_port = Htons (8888);/*4. Bind on Local Port */bind (s, (SOCKADDR *) &saddr, sizeof (SOCKADDR));/*5. Listening Port */ Listen (S, 5); len = sizeof (SOCKADDR); while (1) {/*6. Wait for the client to connect, blocking here until a client connection arrives. */C = Accept (S, (sockaddr*) &caddr, &len); sprintf (SendBuf, "Welcome to my first socket, your IP address:%s\n", Inet_ntoa ( CADDR.SIN_ADDR)/*7. Send data to Client */send (c, SendBuf, strlen (sendbuf) + 1, 0);/*8. Accept the return of the client */recv (c, recvbuf, 1000, 0);/*9. Print out the clientData sent to */printf ("%s\n", recvbuf);/*10. If you no longer contact this client, close it */closesocket (c);} /* If there is a condition for exiting the loop, there is also a need to clear the socket library using *//* wsacleanup (); */return 0;}
Client:
#define _crt_secure_no_warnings#include <stdio.h> #include <winsock2.h> #pragma comment (lib, "Ws2_32.lib" ) int main (void) {wsadata wd;int ret = 0; SOCKET C;char recvbuf[1000] = "", sendbuf[1000] = ""; sockaddr_in Saddr;ret = WSAStartup (Makeword (2, 2), &WD); /*1. Initialization operation */if (ret! = 0) {return 0;} if (Hibyte (wd.wversion)! = 2 | | Lobyte (wd.wversion)! = 2) {printf ("Initialization failed"); WSACleanup (); return 1;} /*2. Create Client SOCKET*/C = socket (af_inet, sock_stream, 0);/*3. Define the service-side information */saddr.sin_addr to be connected. S_un. S_ADDR = inet_addr ("127.0.0.1"); saddr.sin_family = Af_inet;saddr.sin_port = htons (8888);/*4. Connecting the service-side */connect (C, ( sockaddr*) &saddr, sizeof (SOCKADDR)), recv (c, recvbuf, 0);p rintf ("Data sent from the server:%s\n", recvbuf); sprintf (SendBuf, "Hello, service!" "); Send (c, SendBuf, strlen (sendbuf) + 1, 0); closesocket (c); WSACleanup (); GetChar (); return 0;}
C Language Socket Network programming example