└── TCP Server └── main.cpp /TCP Server/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | // #define _WINSOCK_DEPRECATED_NO_WARNINGS 6 | // #define _CRT_SECURE_NO_WARNINGS 7 | // #define NI_MAXHOST 1025 8 | 9 | 10 | #pragma comment(lib, "ws2_32.lib") 11 | 12 | using namespace std; 13 | 14 | int main() { 15 | // Initialize Winsock 16 | WSADATA wsData; 17 | WORD ver = MAKEWORD(2, 2); 18 | 19 | int wsOk = WSAStartup(ver, &wsData); 20 | if (wsOk != 0) { 21 | 22 | cerr << "Cannot initialize winsock. Quitting !!" << endl; 23 | return 1; 24 | } 25 | 26 | //create a socket 27 | SOCKET listening = socket(AF_INET, SOCK_STREAM, 0); 28 | 29 | if (listening == INVALID_SOCKET) { 30 | 31 | cerr << "Cannot create a socket. Quitting !!" << endl; 32 | return 1; 33 | } 34 | 35 | //bind the socket to an ip address and port 36 | 37 | sockaddr_in hint; 38 | hint.sin_family = AF_INET; 39 | hint.sin_port = htons(54000); 40 | hint.sin_addr.S_un.S_addr = INADDR_ANY; //could also use inet_pton 41 | bind(listening, (sockaddr*)&hint, sizeof(hint)); 42 | 43 | //tell winsock the socket is for listening 44 | 45 | listen(listening, SOMAXCONN); 46 | 47 | //wait for a connection 48 | 49 | sockaddr_in client; 50 | int clientsize = sizeof(client); 51 | SOCKET clientsocket = accept(listening, (sockaddr*)&client, &clientsize); 52 | // if (clientsocket == INVALID_SOCKET) //Do something 53 | // { 54 | 55 | // } 56 | char host[NI_MAXHOST]; // client remote name 57 | char service[NI_MAXSERV]; // servuce(i.e port ) the client is connect on 58 | 59 | ZeroMemory(host, NI_MAXHOST); // same as memset(host, 0, NI_MAXHOST); 60 | ZeroMemory(service, NI_MAXSERV); 61 | if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) { 62 | cout << host << "Connected on port " << service << endl; 63 | } 64 | else { 65 | 66 | inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST); 67 | cout << host << "Connected on port " << 68 | ntohs(client.sin_port) << endl; // ntohs = network to host short 69 | } 70 | 71 | //close listening socket 72 | closesocket(listening); 73 | 74 | //while loop: accept and echo message back to client 75 | char buf[4096]; 76 | while (true) { 77 | ZeroMemory(buf, 4096); 78 | //wait for client to send data. 79 | 80 | int bytesReceived = recv(clientsocket, buf, 4096, 0); 81 | if (bytesReceived == SOCKET_ERROR) 82 | { 83 | cerr << " Error in recv(). Quitting " << endl; 84 | break; 85 | } 86 | if (bytesReceived == 0) { 87 | cout << " Client Disconnected. " << endl; 88 | break; 89 | } 90 | send(clientsocket, buf, bytesReceived + 1, 0); 91 | 92 | 93 | //echo message back to the client 94 | } 95 | 96 | //close the socket 97 | 98 | closesocket(clientsocket); 99 | 100 | //Cleanup winsock 101 | 102 | WSACleanup(); 103 | } --------------------------------------------------------------------------------