Always familiar with Socket programming under C / C , and finally completed a very simple Server / Client program today.
Server: #include
Using namespace std;
Const Int my_error = -1;
Int main () {
WSADATA WSADATA; / / Initializing the Windows Socket Library IF (WsaStartup (MakeWord (2, 2), & WSADATA)! = 0) {COUT << "Error In wsastartup << ENDL;
Return my_error;} // Create a socket-> bind-> listen-> accept (blocked) socket server; server = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (server == invalid_socket) {return 0;}
SockAddr_in local; Memset (& local, 0, sizeof (local); local.sin_family = af_INET; local.sin_port = htons (8080); local.sin_addr.s_un.s_addr = HTONL (INADDR_Any);
IF (Bind (SockAddr *) (& local), sizeof (local))! = 0) {cout << "error in bind" << ENDL;
Return my_error;}
IF (Listen (Server, 10)! = 0) {COUT << "Error In Listen" << ENDL;
Return my_error;}
Socket Client; intentdr_in from; int.comlen = sizeof (from); MEMSET (& from, 0, fromlen);
COUT << "Waiting for Connect ..." << endl; client = accept (server, (sockaddr *) (& from), & fromlen
Char Temp [512]; Sprintf (Temp, "Your IP IS% S / R / N", INET_NTOA (from.SIN_ADDR)); Send (Client, Temp, Strlen (Temp), 0); COUT << "Connection from "<< inet_ntoa (from.sin_addr) <<" / r / n "; ClosSocket (Client); CloseSocket;
WSACLEANUP ();
Return 0;}
Client #include
#pragma comment (Lib, "WS2_32.LIB")
Using namespace std; const INT my_error = -1;
Int main () {wsadata wsadata;
IF (WSAStartup (Makeword (2, 2), & WSADATA)! = 0) {cout << "Error In wsastartup << ENDL;
Return my_error;}
Socket conn; conn = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (conn == invalid_socket) {cout << "Error In Socket" << Endl;
Return my_error;}
SockAddr_in Server; MEMSET (Server); Server.sin_Family = AF_INET; Server.SIN_PORT = HTONS (8080); Server.sin_Addr.s_un.s_addr = inet_addr ("192.168.1.99");
IF (CONN, (CONN), SIZEOF (Server))! = 0) {CloseSocket (CONN);
Cout << "Error In Connect" << Endl;
Return my_error;}
CloseSocket (CONN);
WSACLEANUP ();
Return 0;}