#include #include #include #include #include #include #include #include #include #include #define MAX_MSG 1722 #define OUTPUT_FILE "charC.txt" int main (int argc, char** argv) { if (argc != 5) { cout << "charC <# chars> \n"; cout << "\twhere socktype: \n\t\t1 -> SOCK_STREAM\n\t\t2 -> SOCK_CLUSTER\n"; return 1; } int socktype = atoi(argv[1]); if ((socktype <= 0) || (socktype > 2)) { cout << "Socktype must be 1 for SOCK_STREAM or 2 for SOCK_CLUSTER\n"; return 1; } int sockDeclVal = 0; switch(socktype) { case 1: sockDeclVal = SOCK_STREAM; break; case 2: sockDeclVal = SOCK_CLUSTER; break; } FILE* OutputFile = fopen(OUTPUT_FILE, "w+"); if (!OutputFile) { cout << "Failed to write to file " << OUTPUT_FILE; return 1; } int bytesLeft = atoi(argv[2]); char* machineName = argv[3]; int port = atoi(argv[4]); struct hostent* host = gethostbyname(machineName); struct sockaddr_in sockStruct; sockStruct.sin_family = AF_INET; sockStruct.sin_port = port; sockStruct.sin_addr.s_addr = inet_addr(machineName); int desc = socket(PF_INET, sockDeclVal, 0); //0->ip if (desc == -1) { cout << "Error setting protocol\n"; return 1; } if ( connect(desc, (const sockaddr*)&sockStruct, sizeof(sockStruct)) == -1) { cout << "Failed to connect " << strerror(errno) << "\n"; return 1; } char* sentMsg = new char[MAX_MSG+1]; while(bytesLeft) { int msgSize = rand(); msgSize = msgSize % MAX_MSG; if (msgSize > bytesLeft) { msgSize = bytesLeft; } int got = recv(desc, (void*)sentMsg, msgSize, MSG_WAITALL ); if (msgSize != got) { printf ("Only received %d chars\n", got); return 0; } sentMsg[msgSize] = 0; fprintf(OutputFile, "%s", sentMsg); bytesLeft -= msgSize; } close(desc); delete sentMsg; fclose(OutputFile); return 0; };