// // Function: main // // Description: // The main function which loads Winsock, parses the command line, // and initiates either the client or server routine depending // on the parameters passed. // int main(int argc, char **argv) { WSADATA wsd; ValidateArgs(argc, argv); if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { printf("WSAStartup() failed: %d\n", GetLastError()); return -1; } // Check to see if the role of the application is to enumerate local // adapters // if (bEnumerate) EnumerateAdapters(); else { if (bServer) // Act as server Server(); else // Act as client Client(); } closesocket(sock); closesocket(newsock); WSACleanup(); return 0; }
int main(int argc, char** argv) { std::map<std::string, std::string> args = ProcessArgs(argc, argv); if (args.size() != 5 || !ValidateArgs(args)) { ShowHelp(); return -5; } DesuraId id(args["-i"].c_str(), args["-t"].c_str()); if (!Login(args["-u"], args["-p"])) return -1; if (!CreateMcf(id, args["-f"])) return -2; if (!StartUpload(id)) return -3; if (!UploadMcf()) return -4; return 0; }
// // Function: main // // Description: // This function loads Winsock library, parses command line // arguments, creates the appropriate socket (with the right // root or leaf flags), and start the client or server // functions depending on the specified flags. // int main(int argc, char **argv) { WSADATA wsd; SOCKET s; WSAPROTOCOL_INFO lpSocketProtocol; DWORD dwFlags; ValidateArgs(argc, argv); // // Load the Winsock library // if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) { printf("WSAStartup failed\n"); return -1; } // Find an ATM capable protocol // if (FindProtocol(&lpSocketProtocol) == FALSE) { printf("Unable to find ATM protocol entry!\n"); return -1; } // Create the socket using the appripriate root or leaf flags // if (bServer) dwFlags = WSA_FLAG_OVERLAPPED | WSA_FLAG_MULTIPOINT_C_ROOT | WSA_FLAG_MULTIPOINT_D_ROOT; else dwFlags = WSA_FLAG_OVERLAPPED | WSA_FLAG_MULTIPOINT_C_LEAF | WSA_FLAG_MULTIPOINT_D_LEAF; if ((s = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, &lpSocketProtocol, 0, dwFlags)) == INVALID_SOCKET) { printf("socket failed with: %d\n", WSAGetLastError()); WSACleanup(); return -1; } // Start the correct driver depending on what flags were // supplied on the command line. // if (bServer) { Server(s, &lpSocketProtocol); } else { Client(s, &lpSocketProtocol); } closesocket(s); WSACleanup(); return 0; }
// // Function: main // // Description: // Setup the NetBIOS interface, parse the arguments, and call the // adapter status command either locally or remotely depending on // the user supplied arguments. // int main(int argc, char **argv) { LANA_ENUM lenum; int i, num; ValidateArgs(argc, argv); // // Make sure both command line flags weren't set // if (bLocalName && bRemoteName) { printf("usage: astat [/l:LOCALNAME | /r:REMOTENAME]\n"); return 1; } // Enumerate all LANAs and reset each one // if (LanaEnum(&lenum) != NRC_GOODRET) return 1; if (ResetAll(&lenum, (UCHAR)MAX_SESSIONS, (UCHAR)MAX_NAMES, FALSE) != NRC_GOODRET) return 1; // // If we're called with a local name we need to add it to // the name table. // if (bRemoteName == FALSE) { for(i=0; i < lenum.length ;i++) { if (bLocalName) AddName(lenum.lana[i], szLocalName, &num); LanaStatus(lenum.lana[i], szLocalName); } } else { for(i=0; i < lenum.length ;i++) LanaStatus(lenum.lana[i], szRemoteName); } return 0; }
int main(int argc, char **argv) { WSADATA wsd; SOCKET sock; int msg_size; char path[SIZE_BUF]; char name[SIZE_STR]; char buffer[SIZE_BUF]; char author[SIZE_STR]; char command[SIZE_CMD]; char content[SIZE_CONTENT]; ValidateArgs(argc, argv); if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { printf("Failed to load Winsock library!\n"); return 1; } if (binterface) { client.sin_addr.s_addr = inet_addr(szAddress); if (client.sin_addr.s_addr == INADDR_NONE) usage(); } else client.sin_addr.s_addr = htonl(INADDR_ANY); client.sin_family = AF_INET; client.sin_port = htons(port); int len = sizeof(client); if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { printf("Socket is not created: %d\n", WSAGetLastError()); exit(1); } memset(buffer, 0, sizeof(buffer)); while(strcmp(buffer, ":start")) { fgets(buffer, sizeof(buffer), stdin); if (buffer[strlen(buffer) - 1] == '\n') buffer[strlen(buffer) - 1] = '\0'; if ((msg_size = sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client))) == SOCKET_ERROR) { printf("SEND start message failed: %d\n", WSAGetLastError()); exit(1); } } //printf("SEND [%d bytes]: start message '%s'\n", msg_size, buffer); memset(buffer, 0, sizeof(buffer)); if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, &len)) == SOCKET_ERROR) { printf("RECV directory content failed: %d\n", WSAGetLastError()); exit(1); } //printf("RECV [%d bytes]: directory content\n", msg_size); output(buffer); send_report(sock, SUCCESS); while(1) { memset(path, 0, sizeof(path)); if ((msg_size = recvfrom(sock, path, sizeof(path), 0, (struct sockaddr *)&client, &len)) == SOCKET_ERROR) { printf("RECV current path failed: %d\n", WSAGetLastError()); exit(1); } //printf("RECV [%d bytes]: current path '%s'\n", msg_size, path); send_report(sock, SUCCESS); memset(buffer, 0, sizeof(buffer)); if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, &len)) == SOCKET_ERROR) { printf("RECV invitation message failed: %d\n", WSAGetLastError()); exit(1); } //printf("RECV [%d bytes]: invitation message\n", msg_size); output(buffer); char space; memset(name, 0, sizeof(name)); memset(buffer, 0, sizeof(buffer)); memset(author, 0, sizeof(author)); memset(command, 0, sizeof(command)); memset(content, 0, sizeof(content)); scanf("%5s%1c", command, &space); if ((msg_size = sendto(sock, command, strlen(command), 0, (struct sockaddr *)&client, sizeof(client))) == SOCKET_ERROR) { printf("SEND command failed: %d\n", WSAGetLastError()); exit(1); } //printf("SEND [%d bytes]: command '%s'\n", msg_size, path); if (!strcmp(command, ":exit")) { memset(buffer, 0, sizeof(buffer)); if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, &len)) == SOCKET_ERROR) // Receive the content of file { printf("RECV file or directory content failed: %d\n", WSAGetLastError()); exit(1); } //printf("RECV [%d bytes]: file or directory content\n", msg_size); output(buffer); break; } if (recv_report(sock) < 0) { puts("!No such command"); send_report(sock, SUCCESS); } if (!strcmp(command, "add")) { char str[SIZE_ARG]; fgets(name, sizeof(name), stdin); if (name[strlen(name) - 1] == '\n') name[strlen(name) - 1] = '\0'; if ((msg_size = sendto(sock, name, strlen(name), 0, (struct sockaddr *)&client, sizeof(client))) == SOCKET_ERROR) { printf("SEND command failed: %d\n", WSAGetLastError()); exit(1); } //printf("SEND [%d bytes]: title of article '%s'\n", msg_size, name); if (recv_report(sock) < 0) { puts("!Such file already exist"); send_report(sock, SUCCESS); } else { int length = sizeof(content) - sizeof(author) - sizeof(name); printf("Input author: "); fgets(author, sizeof(author), stdin); if (author[strlen(author) - 1] == '\n') author[strlen(author) - 1] = '\0'; printf("name's read: %s [%d bytes]\n", name, msg_size); printf("author's read: %s [%d bytes]\n", author, msg_size); puts("Put content:"); printf("[%d of %d] ", (strlen(content)+strlen(str)), length); while (fgets(str, sizeof(str), stdin) != NULL) { if (!strncmp(":end", str, strlen(":end"))) break; if ((strlen(content)+strlen(str)) > length) { puts("!Text size will not allow"); memset(str, 0, strlen(str)); printf("[%d of %d] ",(strlen(content)+strlen(str)), length ); } strcat(content, str); memset(str, 0, strlen(str)); } if ((msg_size = sendto(sock, author, strlen(author), 0, (struct sockaddr *)&client, sizeof(client))) == SOCKET_ERROR) { printf("SEND author of article failed: %d\n", WSAGetLastError()); exit(1); } //printf("SEND [%d bytes]: author of article '%s'\n", msg_size, author); recv_report(sock); if ((msg_size = sendto(sock, content, strlen(content), 0, (struct sockaddr *)&client, sizeof(client))) == SOCKET_ERROR) { printf("SEND file content failed: %d\n", WSAGetLastError()); exit(1); } //printf("SEND [%d bytes]: file content '%s'\n", msg_size, content); if (recv_report(sock) < 0) puts("!Such file already exist"); send_report(sock, SUCCESS); } } gets(buffer); if (!strcmp(command, "open")) { strcat(path, buffer); if ((msg_size = sendto(sock, path, strlen(path), 0, (struct sockaddr *)&client, sizeof(client))) == SOCKET_ERROR) { printf("SEND full path to file failed: %d\n", WSAGetLastError()); exit(1); } //printf("SEND [%d bytes]: full path to file '%s'\n", msg_size, path); } else if (!strcmp(command, "find")) { if ((msg_size = sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client))) == SOCKET_ERROR) { printf("SEND author to find failed: %d\n", WSAGetLastError()); exit(1); } //printf("SEND [%d bytes]: author to find '%s'\n", msg_size, buffer); } memset(content, 0, sizeof(content)); if ((msg_size = recvfrom(sock, content, sizeof(content), 0, (struct sockaddr *)&client, &len)) == SOCKET_ERROR) // Receive the content of file { printf("RECV file or directory content failed: %d\n", WSAGetLastError()); exit(1); } //printf("RECV [%d bytes]: file or directory content\n", msg_size); output(content); send_report(sock, SUCCESS); } closesocket(sock); WSACleanup(); return 0; }
// // Function: main // // Description: // Parse the command line arguments, load the Winsock library, // create a socket and join the multicast group. If this program // is started as a sender then begin sending messages to the // multicast group; otherwise, call recvfrom() to read messages // sent to the group. // int main(int argc, char **argv) { WSADATA wsd; struct sockaddr_in local, remote, from; struct ip_mreq mcast; SOCKET sockM; TCHAR recvbuf[BUFSIZE], sendbuf[BUFSIZE]; int len = sizeof(struct sockaddr_in), optval, ret; DWORD i=0; // Parse the command line and load Winsock // ValidateArgs(argc, argv); if (WSAStartup(MAKEWORD(1, 1), &wsd) != 0) { printf("WSAStartup failed\n"); return -1; } // Create the socket. In Winsock 1 you don't need any special // flags to indicate multicasting. // if ((sockM = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) { printf("socket failed with: %d\n", WSAGetLastError()); WSACleanup(); return -1; } // Bind the socket to the local interface. This is done so // that we can receive data. // local.sin_family = AF_INET; local.sin_port = htons(iPort); local.sin_addr.s_addr = dwInterface; if (bind(sockM, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR) { printf("bind failed with: %d\n", WSAGetLastError()); closesocket(sockM); WSACleanup(); return -1; } // Setup the im_req structure to indicate what group we want // to join as well as the interface // remote.sin_family = AF_INET; remote.sin_port = htons(iPort); remote.sin_addr.s_addr = dwMulticastGroup; mcast.imr_multiaddr.s_addr = dwMulticastGroup; mcast.imr_interface.s_addr = dwInterface; if (setsockopt(sockM, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mcast, sizeof(mcast)) == SOCKET_ERROR) { printf("setsockopt(IP_ADD_MEMBERSHIP) failed: %d\n", WSAGetLastError()); closesocket(sockM); WSACleanup(); return -1; } // Set the TTL to something else. The default TTL is 1. // optval = 8; if (setsockopt(sockM, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&optval, sizeof(int)) == SOCKET_ERROR) { printf("setsockopt(IP_MULTICAST_TTL) failed: %d\n", WSAGetLastError()); closesocket(sockM); WSACleanup(); return -1; } // Disable the loopback if selected. Note that on NT4 and Win95 // you cannot disable it. // if (bLoopBack) { optval = 0; if (setsockopt(sockM, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&optval, sizeof(optval)) == SOCKET_ERROR) { printf("setsockopt(IP_MULTICAST_LOOP) failed: %d\n", WSAGetLastError()); closesocket(sockM); WSACleanup(); return -1; } } if (!bSender) // Receiver { // Receive some data // for(i = 0; i < dwCount; i++) { if ((ret = recvfrom(sockM, recvbuf, BUFSIZE, 0, (struct sockaddr *)&from, &len)) == SOCKET_ERROR) { printf("recvfrom failed with: %d\n", WSAGetLastError()); closesocket(sockM); WSACleanup(); return -1; } recvbuf[ret] = 0; printf("RECV: '%s' from <%s>\n", recvbuf, inet_ntoa(from.sin_addr)); } } else // Sender { // Send some data // for(i = 0; i < dwCount; i++) { sprintf(sendbuf, "server 1: This is a test: %d", i); if (sendto(sockM, (char *)sendbuf, strlen(sendbuf), 0, (struct sockaddr *)&remote, sizeof(remote)) == SOCKET_ERROR) { printf("sendto failed with: %d\n", WSAGetLastError()); closesocket(sockM); WSACleanup(); return -1; } Sleep(500); } } // Drop group membership // if (setsockopt(sockM, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&mcast, sizeof(mcast)) == SOCKET_ERROR) { printf("setsockopt(IP_DROP_MEMBERSHIP) failed: %d\n", WSAGetLastError()); } closesocket(sockM); WSACleanup(); return 0; }
int _tmain(int argc, _TCHAR* argv[]) { ValidateArgs(argc,argv); HANDLE hDisk = CreateFile(g_szDeviceName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (hDisk == INVALID_HANDLE_VALUE) { DWORD dwError = GetLastError(); std::cout << red << "Open Disk Error---" << dwError << white << std::endl; return 2; } HANDLE hFile = INVALID_HANDLE_VALUE; if (g_bRead) { hFile = CreateFile(g_szFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_FLAG_OVERLAPPED, NULL); } else if (g_bWrite) { hFile = CreateFile(g_szFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); DWORD dwErrorCode = 0; SetDiskAtrribute(hDisk,FALSE,TRUE,&dwErrorCode); } else if (g_bVerify) { hFile = CreateFile(g_szFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); } else if (g_bErase) { } else { CloseHandle(hDisk); Usage(); return 2; } if (!g_bErase) { if (hFile == INVALID_HANDLE_VALUE) { DWORD dwError = GetLastError(); std::cout << red << "Open File Error---" << dwError << white << std::endl; CloseHandle(hDisk); return 2; } } memset(&g_OverlapedDisk,0,sizeof(g_OverlapedDisk)); memset(&g_OverlapedFile,0,sizeof(g_OverlapedFile)); g_OverlapedDisk.hEvent = CreateEvent(NULL,FALSE,TRUE,NULL); g_OverlapedFile.hEvent = CreateEvent(NULL,FALSE,TRUE,NULL); ULONGLONG ullSumSectors = GetDiskSectors(hDisk); BOOL bOK = TRUE; if (g_bRead) { if ((g_ullSectors == -1) || ((g_ullSectors + g_ullStartSector) > ullSumSectors)) { g_ullSectors = ullSumSectors - g_ullStartSector; } std::cout << yellow << "Running --- Read Disk to File ......" << white << std::endl; bOK = ReadDiskToFile(hDisk,hFile,g_ullStartSector,g_ullSectors); if (bOK) { std::cout << green << "Read Disk to File --- PASS, PASS, PASS !" << white << std::endl; } } else if (g_bWrite) { ULONGLONG ullFileSectors = GetFileSectors(hFile); if (ullSumSectors> ullFileSectors) { ullSumSectors = ullFileSectors; } std::cout << yellow << "Running --- Write Disk from File ......" << white << std::endl; if ((g_ullSectors == -1) || ((g_ullSectors + g_ullStartSector) > ullSumSectors) ) { g_ullSectors = ullSumSectors - g_ullStartSector; } bOK = WriteDiskFromFile(hDisk,hFile,g_ullStartSector,g_ullSectors); if (bOK) { std::cout << green << "Write Disk from File --- PASS, PASS, PASS !" << white << std::endl; } } else if (g_bVerify) { ULONGLONG ullFileSectors = GetFileSectors(hFile); if (ullSumSectors> ullFileSectors) { ullSumSectors = ullFileSectors; } if ((g_ullSectors == -1) || ((g_ullSectors + g_ullStartSector) > ullSumSectors) ) { g_ullSectors = ullSumSectors - g_ullStartSector; } std::cout << yellow << "Running --- Verify Disk and File ......" << white << std::endl; bOK = VerifyDiskAndFile(hDisk,hFile,g_ullStartSector,g_ullSectors); if (bOK) { std::cout << green << "Verify Disk and File --- PASS, PASS, PASS !" << white << std::endl; } } else if (g_bErase) { std::cout << yellow << "Running --- Erase Disk ......" << white << std::endl; if ((g_ullSectors == -1) || ((g_ullSectors + g_ullStartSector) > ullSumSectors) ) { g_ullSectors = ullSumSectors - g_ullStartSector; } bOK = EraseDisk(hDisk,g_ullStartSector,g_ullSectors); if (bOK) { std::cout << green << "Write Disk from File --- PASS, PASS, PASS !" << white << std::endl; } } else { bOK = FALSE; Usage(); } if (g_bVerify && (g_bWrite || g_bRead ) && bOK && !g_bErase) { std::cout << yellow << "Running --- Verify Disk and File ......" << white << std::endl; bOK = VerifyDiskAndFile(hDisk,hFile,g_ullStartSector,g_ullSectors); if (bOK) { std::cout << green << "Verify Disk and File --- PASS, PASS, PASS !" << white << std::endl; } } CloseHandle(hFile); CloseHandle(hDisk); if (g_OverlapedDisk.hEvent != NULL) { CloseHandle(g_OverlapedDisk.hEvent); } if (g_OverlapedFile.hEvent != NULL) { CloseHandle(g_OverlapedFile.hEvent); } if (bOK) { std::cout << green << "Operation Success !!!" << white << std::endl; } std::cout << std::endl; return 0; }
//主函数:main //初始化winsock,分析命令行参数,创建套接字,连接服务器,发送和接收数据 int main(int argc, char **argv) { WSADATA wsd; SOCKET sClient; char szBuffer[DEFAULT_BUFFER]; int ret, i; struct sockaddr_in server; struct hostent *host = NULL; if (argc < 2){ usage(); exit(1); } //分析命令行参数,加载winsock ValidateArgs(argc, argv); if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0){ printf("Failed to load winsock library! error %d\n",WSAGetLastError()); return 1; } else printf("winsock library loaded successfully!\n"); strcpy_s(szMessage, sizeof(szMessage), DEFAULT_MESSAGE); //创建套接字,连接服务器 sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sClient == INVALID_SOCKET){ printf("socket() failed with error code %d\n",WSAGetLastError()); return 1; } else printf("socket() looks fine!\n"); server.sin_family = AF_INET; server.sin_port = htons(iPort); server.sin_addr.s_addr = inet_addr(szServer); //如果服务器地址不是aaa.bbb.ccc.ddd格式,就是主机名,需要解析 if (server.sin_addr.s_addr == INADDR_NONE){ host = gethostbyname(szServer); if (host == NULL){ printf("unable to resolve server %s\n",szServer); return 1; } else printf("The hostname resolved successfully!\n"); CopyMemory(&server.sin_addr, host->h_addr_list[0], host->h_length); } if (connect(sClient, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR){ printf("connect() failed with error code %d\n",WSAGetLastError()); return 1; } else printf("connect() is pretty damn fine!\n"); //发送和接收数据 printf("sending and receiving data if any...\n"); for (i = 0; i < (int)dwCount; i++){ ret = send(sClient, szMessage, strlen(szMessage),0); if (ret == 0) break; else if (ret == SOCKET_ERROR){ printf("send() failed with error code %d\n",WSAGetLastError()); break; } printf("send() should be fine.send %d butys\n",ret); if (!bSendOnly){ ret = recv(sClient, szBuffer, DEFAULT_BUFFER, 0); if (ret == 0){ printf("it is a graceful close!\n"); break; } else if (ret == SOCKET_ERROR){ printf("recv() failed with error code %d\n",WSAGetLastError()); break; } szBuffer[ret] = '\0'; printf("recv() is OK,Received %d bytes:%s\n",ret,szBuffer); } } if (closesocket(sClient) == 0) printf("closesocket() is OK!\n"); else printf("closesocket() failed with error code %d\n",WSAGetLastError()); if (WSACleanup() == 0) printf("WSACleanup() is fine!\n"); else printf("WSACleanup() with error code %d\n", WSAGetLastError()); return 0; }
int main(int argc,char **argv) { WSADATA wsd; SOCKET sListen,sClient; int iAddrSize; HANDLE hThread; DWORD dwThreadId; struct sockaddr_in local,client; ValidateArgs(argc,argv); if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { printf("Failed to load Winsock!\n"); return 1; } sListen = socket(AF_INET,SOCK_STREAM,IPPROTO_IP); if(sListen == SOCKET_ERROR) { printf("socket() failed:%d\n",WSAGetLastError()); return 1; } if(bInterface) { local.sin_addr.s_addr = inet_addr(szAddress); if(local.sin_addr.s_addr==INADDR_NONE) useage(); } else local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_family = AF_INET; local.sin_port = htons(iPort); if(bind(sListen,(struct sockaddr*)&local,sizeof(local)) == SOCKET_ERROR) { printf("bind() failed: %d\n",WSAGetLastError()); return 1; }; listen(sListen,8); while(1) { iAddrSize = sizeof(client); sClient = accept(sListen,(struct sockaddr*)&client,&iAddrSize); if(sClient == INVALID_SOCKET) { printf("accept() failed: %d\n",WSAGetLastError()); break; } printf("Accepted client:%s:%d\n", inet_ntoa(client.sin_addr),ntohs(client.sin_port)); hThread = CreateThread(NULL,0,ClientThread,(LPVOID)sClient,0,&dwThreadId); if(hThread == NULL) { printf("CreateThread() failed: %d\n",GetLastError()); break; } CloseHandle(hThread); } printf("close sock\n\n"); closesocket(sListen); WSACleanup(); return 0; }
// // Function: main // // Description: // Parse the command line arguments, load the Winsock library, // create a socket and join the multicast group. If set as a // sender then begin sending messages to the multicast group; // otherwise, call recvfrom() to read messages send to the // group. // int _cdecl main(int argc, char **argv) { WSADATA wsd; SOCKET s, sc; SOCKADDR_STORAGE remote; struct addrinfo *resmulti=NULL, *resif=NULL, *resbind=NULL; char *buf=NULL; int remotelen, err, rc, i=0; // Parse the command line ValidateArgs(argc, argv); // Load Winsock if (WSAStartup(MAKEWORD(1, 1), &wsd) != 0) { printf("WSAStartup failed\n"); return -1; } // Resolve the multicast address resmulti = ResolveAddress(gMulticast, gPort, AF_INET, 0, 0); if (resmulti == NULL) { fprintf(stderr, "Unable to convert multicast address '%s': %d\n", gMulticast, WSAGetLastError()); return -1; } // // Create the socket. In Winsock 1 you don't need any special // flags to indicate multicasting. // s = socket(resmulti->ai_family, gSocketType, gProtocol); if (s == INVALID_SOCKET) { printf("socket failed with: %d\n", WSAGetLastError()); return -1; } printf("socket handle = 0x%p\n", s); // Allocate the send/receive buffer buf = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, gBufferSize); if (buf == NULL) { fprintf(stderr, "HeapAlloc failed: %d\n", GetLastError()); return -1; } if (bSender) { // Bind to the wildcard address resbind = ResolveAddress(NULL, gPort, AF_INET, 0, 0); if (resbind == NULL) { fprintf(stderr, "Unable to obtain bind address!\n"); return -1; } // Bind the socket rc = bind(s, resbind->ai_addr, resbind->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind failed: %d\n", WSAGetLastError()); return -1; } freeaddrinfo(resbind); // If sepcified, set the send interface if (gInterfaceCount == 1) { resif = ResolveAddress(gListenInterface[0], gPort, AF_INET, 0, 0); if (resif == NULL) { return -1; } rc = SetSendInterface(s, resif); freeaddrinfo(resif); // Set the TTL to something else. The default TTL is one. rc = SetMulticastTtl(s, resmulti->ai_family, gTtl); if (rc == SOCKET_ERROR) { return -1; } } // If specified set the late joiner option if (gLateJoin != -1) { SetLateJoin(s, gLateJoin); } // If specified set the window paramters if (bSetSendWindow) { SetWindowSize(s, gWindowSizeBytes, gWindowSizeMSec, gWindowRateKbitsSec); } // If specified set the FEC paramters if (bUseFec == TRUE) { SetFecParameters(s, gFecBlockSize, gFecGroupSize, bFecOnDemand, gFecProActive); } // Connect the socket to the multicast group the session is to be on rc = connect(s, resmulti->ai_addr, resmulti->ai_addrlen); if (rc == SOCKET_ERROR) { printf("connect failed: %d\n", WSAGetLastError()); return -1; } memset(buf, '^', gBufferSize); // Send some data for(i=0; i < gCount ; i++) { rc = send( s, buf, gBufferSize, 0 ); if (rc == SOCKET_ERROR) { fprintf(stderr, "send failed with: %d\n", WSAGetLastError()); return -1; } printf("SENT %d bytes\n", rc); } } else { // Bind the socket to the multicast address on which the session will take place rc = bind(s, resmulti->ai_addr, resmulti->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind failed: %d\n", WSAGetLastError()); return -1; } printf("Binding to "); PrintAddress(resmulti->ai_addr, resmulti->ai_addrlen); printf("\n"); // Add each supplied interface as a receive interface if (gInterfaceCount > 0) { for(i=0; i < gInterfaceCount ;i++) { resif = ResolveAddress(gListenInterface[i], "0", AF_INET, 0, 0); if (resif == NULL) { return -1; } rc = AddReceiveInterface(s, resif); freeaddrinfo(resif); } } // Listen for sessions rc = listen(s, 1); if (rc == SOCKET_ERROR) { fprintf(stderr, "listen failed: %d\n", WSAGetLastError()); return -1; } // Wait for a session to become available remotelen = sizeof(remote); sc = accept(s, (SOCKADDR *)&remote, &remotelen); if (sc == INVALID_SOCKET) { fprintf(stderr, "accept failed: %d\n", WSAGetLastError()); return -1; } printf("Join multicast session from: "); PrintAddress((SOCKADDR *)&remote, remotelen); printf("\n"); while (1) { // Receive data until an error or until the session is closed rc = recv(sc, buf, gBufferSize, 0); if (rc == SOCKET_ERROR) { if ((err = WSAGetLastError()) != WSAEDISCON) { fprintf(stderr, "recv failed: %d\n", err); } break; } else { printf("received %d bytes\n", rc); } } // Close the session socket closesocket(sc); } // Clean up freeaddrinfo(resmulti); closesocket(s); WSACleanup(); return 0; }
// // Function: main // // Description: // This function loads Winsock, parses the command line, and // begins receiving packets. Once a packet is received they // are decoded. Because we are receiving IP datagrams, the // receive call will return whole datagrams. // int __cdecl main(int argc, char **argv) { SOCKET s = INVALID_SOCKET; WSADATA wsd; WSABUF wbuf = {0}; DWORD dwBytesRet = 0, dwFlags = 0; char *rcvbuf=NULL; int rc = 0, err; // // Load Winsock // if ((rc = WSAStartup(MAKEWORD(2,2), &wsd)) != 0) { printf("WSAStartup() failed: %d\n", rc); return -1; } // // Parse the command line // if (ValidateArgs(argc, argv) == SOCKET_ERROR) { usage(argv[0]); } if ( g_ulFilterMask & (FILTER_MASK_SOURCE_ADDRESS | FILTER_MASK_SOURCE_PORT) ) { printf("Source address filter : "); PrintAddress((SOCKADDR *)&g_saSourceAddress, sizeof(g_saSourceAddress)); printf("\n"); } if ( g_ulFilterMask & (FILTER_MASK_DESTINATION_ADDRESS | FILTER_MASK_DESTINATION_PORT) ) { printf("Destination address filter: "); PrintAddress((SOCKADDR *)&g_saDestinationAddress, sizeof(g_saDestinationAddress)); printf("\n"); } // // Create a raw socket for receiving IP datagrams // s = WSASocket(g_saLocalInterface.ss_family, SOCK_RAW, g_dwProtocol, NULL, 0, WSA_FLAG_OVERLAPPED); if (s == INVALID_SOCKET) { printf("WSASocket() failed: %d\n", WSAGetLastError()); return -1; } // // This socket MUST be bound before calling the ioctl // rc = bind(s, (SOCKADDR *)&g_saLocalInterface, sizeof(g_saLocalInterface)); if (rc == SOCKET_ERROR) { printf("bind() failed: %d\n", WSAGetLastError()); if (INVALID_SOCKET != s) { closesocket(s); s = INVALID_SOCKET; } WSACleanup(); return -1; } printf("Binding to: "); PrintAddress((SOCKADDR *)&g_saLocalInterface, sizeof(g_saLocalInterface)); printf("\n"); // // Set the SIO_RCVALLxxx ioctl // rc = WSAIoctl(s, g_dwIoControlCode, &g_dwIoControlValue, sizeof(g_dwIoControlValue), NULL, 0, &dwBytesRet, NULL, NULL); if (rc == SOCKET_ERROR) { printf("WSAIotcl(0x%x) failed: %d\n", g_dwIoControlCode, (err = WSAGetLastError())); if (err == WSAEINVAL) { printf("NOTE: IPv6 does not currently support the SIO_RCVALL* ioctls\n"); } if (INVALID_SOCKET != s) { closesocket(s); s = INVALID_SOCKET; } WSACleanup(); return -1; } // // Allocate a buffer for receiving data // rcvbuf = (char *)HeapAlloc(GetProcessHeap(), 0, MAX_IP_SIZE); if (rcvbuf == NULL) { fprintf(stderr, "HeapAlloc failed: %d\n", GetLastError()); if (INVALID_SOCKET != s) { closesocket(s); s = INVALID_SOCKET; } WSACleanup(); return -1; } // // Start receiving IP datagrams until interrupted // while (1) { wbuf.len = MAX_IP_SIZE; wbuf.buf = rcvbuf; dwFlags = 0; rc = WSARecv(s, &wbuf, 1, &dwBytesRet, &dwFlags, NULL, NULL); if (rc == SOCKET_ERROR) { printf("WSARecv() failed: %d\n", WSAGetLastError()); break; } // Decode the IP header // rc = DecodeIPHeader( rcvbuf, dwBytesRet, g_ulFilterMask, (SOCKADDR *)&g_saSourceAddress, (SOCKADDR *)&g_saDestinationAddress ); if (rc != NO_ERROR) { printf("Error decoding IP header!\n"); break; } } // // Cleanup // if (rcvbuf) HeapFree(GetProcessHeap(), 0, rcvbuf); if (INVALID_SOCKET != s) { closesocket(s); s = INVALID_SOCKET; } WSACleanup(); return 0; }
// // Function: main // // Description: // This is the main program. It parses the command line and creates // the main socket. For UDP this socket is used to receive datagrams. // For TCP the socket is used to accept incoming client connections. // Each client TCP connection is handed off to a worker thread which // will receive any data on that connection until the connection is // closed. // int __cdecl main(int argc, char **argv) { WSADATA wsd; THREAD_OBJ *thread=NULL; SOCKET_OBJ *sockobj=NULL, *newsock=NULL; int index, rc; struct addrinfo *res=NULL, *ptr=NULL; // Validate the command line ValidateArgs(argc, argv); // Load Winsock if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { fprintf(stderr, "unable to load Winsock!\n"); return -1; } printf("Local address: %s; Port: %s; Family: %d\n", gBindAddr, gBindPort, gAddressFamily); res = ResolveAddress(gBindAddr, gBindPort, gAddressFamily, gSocketType, gProtocol); if (res == NULL) { fprintf(stderr, "ResolveAddress failed to return any addresses!\n"); return -1; } thread = GetThreadObj(); // For each local address returned, create a listening/receiving socket ptr = res; while (ptr) { PrintAddress(ptr->ai_addr, ptr->ai_addrlen); printf("\n"); sockobj = GetSocketObj(INVALID_SOCKET, (gProtocol == IPPROTO_TCP) ? TRUE : FALSE); // create the socket sockobj->s = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (sockobj->s == INVALID_SOCKET) { fprintf(stderr,"socket failed: %d\n", WSAGetLastError()); return -1; } InsertSocketObj(thread, sockobj); // bind the socket to a local address and port rc = bind(sockobj->s, ptr->ai_addr, ptr->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind failed: %d\n", WSAGetLastError()); return -1; } if (gProtocol == IPPROTO_TCP) { rc = listen(sockobj->s, 200); if (rc == SOCKET_ERROR) { fprintf(stderr, "listen failed: %d\n", WSAGetLastError()); return -1; } // Register events on the socket rc = WSAEventSelect( sockobj->s, sockobj->event, FD_ACCEPT | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAEventSelect failed: %d\n", WSAGetLastError()); return -1; } } else { // Register events on the socket rc = WSAEventSelect( sockobj->s, sockobj->event, FD_READ | FD_WRITE | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAEventSelect failed: %d\n", WSAGetLastError()); return -1; } } ptr = ptr->ai_next; } // free the addrinfo structure for the 'bind' address freeaddrinfo(res); gStartTime = gStartTimeLast = GetTickCount(); while (1) { rc = WaitForMultipleObjects( thread->SocketCount + 1, thread->Handles, FALSE, 5000 ); if (rc == WAIT_FAILED) { fprintf(stderr, "WaitForMultipleObjects failed: %d\n", GetLastError()); break; } else if (rc == WAIT_TIMEOUT) { PrintStatistics(); } else { index = rc - WAIT_OBJECT_0; sockobj = FindSocketObj(thread, index-1); if (gProtocol == IPPROTO_TCP) { SOCKADDR_STORAGE sa; WSANETWORKEVENTS ne; SOCKET sc; int salen; rc = WSAEnumNetworkEvents( sockobj->s, thread->Handles[index], &ne ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAEnumNetworkEvents failed: %d\n", WSAGetLastError()); break; } while (1) { sc = INVALID_SOCKET; salen = sizeof(sa); // // For TCP, accept the connection and hand off the client socket // to a worker thread // sc = accept( sockobj->s, (SOCKADDR *)&sa, &salen ); if ((sc == INVALID_SOCKET) && (WSAGetLastError() != WSAEWOULDBLOCK)) { fprintf(stderr, "accept failed: %d\n", WSAGetLastError()); break; } else if (sc != INVALID_SOCKET) { newsock = GetSocketObj(INVALID_SOCKET, FALSE); // Copy address information memcpy(&newsock->addr, &sa, salen); newsock->addrlen = salen; newsock->s = sc; InterlockedIncrement(&gTotalConnections); InterlockedIncrement(&gCurrentConnections); /* printf("Accepted connection from: "); PrintAddress((SOCKADDR *)&newsock->addr, newsock->addrlen); printf("\n"); */ // Register for read, write and close on the client socket rc = WSAEventSelect( newsock->s, newsock->event, FD_READ | FD_WRITE | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAEventSelect failed: %d\n", WSAGetLastError()); break; } AssignToFreeThread(newsock); } else { // Failed with WSAEWOULDBLOCK -- just continue break; } } } else { // For UDP all we have to do is handle events on the main // threads. if (HandleIo(thread, sockobj) == SOCKET_ERROR) { RenumberThreadArray(thread); } } } } WSACleanup(); return 0; }
// // Function: main // // Description: // Main thread of execution. Initialize Winsock, parse the command // line arguments, create a socket, bind it to a local interface // and port, and then read datagrams. // int main(int argc, char **argv) { WSADATA wsd; SOCKET s; char *recvbuf = NULL; int ret, i; DWORD dwSenderSize; SOCKADDR_IN sender, local; // Parse arguments and load Winsock // ValidateArgs(argc, argv); if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { printf("WSAStartup failed!\n"); return 1; } // Create the socket and bind it to a local interface and port // s = socket(AF_INET, SOCK_DGRAM, 0); if (s == INVALID_SOCKET) { printf("socket() failed; %d\n", WSAGetLastError()); return 1; } local.sin_family = AF_INET; local.sin_port = htons((short)iPort); if (bInterface) local.sin_addr.s_addr = inet_addr(szInterface); else local.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(s, (SOCKADDR *)&local, sizeof(local)) == SOCKET_ERROR) { printf("bind() failed: %d\n", WSAGetLastError()); return 1; } // Allocate the receive buffer // recvbuf = GlobalAlloc(GMEM_FIXED, dwLength); if (!recvbuf) { printf("GlobalAlloc() failed: %d\n", GetLastError()); return 1; } // Read the datagrams // for(i = 0; i < dwCount; i++) { dwSenderSize = sizeof(sender); ret = recvfrom(s, recvbuf, dwLength, 0, (SOCKADDR *)&sender, &dwSenderSize); if (ret == SOCKET_ERROR) { printf("recvfrom() failed; %d\n", WSAGetLastError()); break; } else if (ret == 0) break; else { recvbuf[ret] = '\0'; printf("[%s] sent me: '%s'\n", inet_ntoa(sender.sin_addr), recvbuf); } } closesocket(s); GlobalFree(recvbuf); WSACleanup(); return 0; }
// // Function: main // // Description: // This is the main program. It parses the command line and creates // the main socket. For UDP this socket is used to receive datagrams. // For TCP the socket is used to accept incoming client connections. // Each client TCP connection is handed off to a worker thread which // will receive any data on that connection until the connection is // closed. // int __cdecl main(int argc, char **argv) { WSADATA wsd; SOCKET_OBJ *sockobj=NULL, *sptr=NULL, *tmp=NULL; HANDLE hThread; ULONG lastprint=0; MSG msg; int rc; struct addrinfo *res=NULL, *ptr=NULL; ValidateArgs(argc, argv); InitializeCriticalSection(&gSocketCritSec); // Load winsock if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { fprintf(stderr, "unable to load Winsock!\n"); return -1; } gWorkerWindow = MakeWorkerWindow(); printf("Local address: %s; Port: %s; Family: %d\n", gBindAddr, gBindPort, gAddressFamily); res = ResolveAddress(gBindAddr, gBindPort, gAddressFamily, gSocketType, gProtocol); if (res == NULL) { fprintf(stderr, "ResolveAddress failed to return any addresses!\n"); return -1; } // For each local address returned, create a listening/receiving socket ptr = res; while (ptr) { PrintAddress(ptr->ai_addr, ptr->ai_addrlen); printf("\n"); sockobj = GetSocketObj(INVALID_SOCKET); // create the socket sockobj->s = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (sockobj->s == INVALID_SOCKET) { fprintf(stderr,"socket failed: %d\n", WSAGetLastError()); return -1; } InsertSocketObj(sockobj); // bind the socket to a local address and port rc = bind(sockobj->s, ptr->ai_addr, ptr->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind failed: %d\n", WSAGetLastError()); return -1; } if (gProtocol == IPPROTO_TCP) { rc = listen(sockobj->s, 200); if (rc == SOCKET_ERROR) { fprintf(stderr, "listen failed: %d\n", WSAGetLastError()); return -1; } // Register for notification rc = WSAAsyncSelect( sockobj->s, gWorkerWindow, WM_SOCKET, FD_ACCEPT | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAAsyncSelect failed: %d\n", WSAGetLastError()); return -1; } } else { // Register for notification rc = WSAAsyncSelect( sockobj->s, gWorkerWindow, WM_SOCKET, FD_READ | FD_WRITE | FD_CLOSE ); if (rc == SOCKET_ERROR) { fprintf(stderr, "WSAAsyncSelect failed: %d\n", WSAGetLastError()); return -1; } } ptr = ptr->ai_next; } // free the addrinfo structure for the 'bind' address freeaddrinfo(res); gStartTime = gStartTimeLast = lastprint = GetTickCount(); // Start a thread to print statistics hThread = CreateThread(NULL, 0, StatisticsThread, NULL, 0, NULL); if (hThread == NULL) { fprintf(stderr, "CreateThread failed: %d\n", WSAGetLastError()); return -1; } CloseHandle(hThread); while(rc = GetMessage(&msg, NULL, 0, 0)) { if (rc == -1) { fprintf(stderr, "GetMessage() failed with error %d\n", GetLastError()); return -1; } TranslateMessage(&msg); DispatchMessage(&msg); } WSACleanup(); DeleteCriticalSection(&gSocketCritSec); return 0; }
int main(int argc, char* argv[]) { ValidateArgs(argc,argv); CLisence lisence; BYTE byKey[KEY_LEN] = {0}; if (g_bLockFile) { BYTE *pByte = lisence.GetKeyFromFile(g_szLockFile); memcpy(byKey,pByte,KEY_LEN); } else if (g_bLockString) { // 把string转换成byte; BYTE *pLock = new BYTE[strlen(g_szLockString) / 2]; memset(pLock,0,strlen(g_szLockString) / 2); int len = StringToByte(pLock,g_szLockString); BYTE *pByte = lisence.GetKey(pLock,len); memcpy(byKey,pByte,KEY_LEN); delete []pLock; } else { BYTE *pByte = lisence.GetLock(); printf("Machine Lock Code:\n"); for (int i = 0;i < LOCK_LEN;i++) { printf("%02X",pByte[i]); } printf("\n\n"); pByte = lisence.GetKey(); memcpy(byKey,pByte,KEY_LEN); } FILE *fp = fopen(LISENCE_FILE,"wb"); if (fp != NULL) { fwrite(byKey,1,sizeof(byKey),fp); fclose(fp); printf("Generate Key:\n"); for (int i = 0; i < KEY_LEN;i++) { printf("%02X",byKey[i]); } printf("\n\n"); return 0; } else { printf("create %s file error\n\n",LISENCE_FILE); return 1; } }
int main(int argc, char **argv) { int sock; int msg_size; char name[SIZE_STR]; char path[SIZE_BUF]; char author[SIZE_STR]; char buffer[SIZE_BUF]; char command[SIZE_CMD]; char content[SIZE_CONTENT]; ValidateArgs(argc, argv); if (interface) { client.sin_addr.s_addr = inet_addr(szAddress); if (client.sin_addr.s_addr == INADDR_NONE) usage(); } else client.sin_addr.s_addr = htonl(INADDR_ANY); client.sin_family = AF_INET; client.sin_port = htons(port); int len = sizeof(client); if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("Socket is not created"); exit(1); } bzero(buffer, sizeof(buffer)); while(strcmp(buffer, ":start")) { fgets(buffer, sizeof(buffer), stdin); if (buffer[strlen(buffer) - 1] == '\n') buffer[strlen(buffer) - 1] = '\0'; if ((msg_size = sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client))) < 0) { perror("SEND start message failed"); exit(1); } } //printf("SEND [%d bytes]: start message '%s'\n", msg_size, buffer); bzero(buffer, sizeof(buffer)); if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0) { perror("RECV directory content failed"); exit(1); } //printf("RECV [%d bytes]: directory content\n", msg_size); output(buffer); send_report(sock, SUCCESS); while(1) { bzero(path, sizeof(path)); if ((msg_size = recvfrom(sock, path, sizeof(path), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0) { perror("RECV current path failed"); exit(1); } //printf("RECV [%d bytes]: current path '%s'\n", msg_size, path); send_report(sock, SUCCESS); bzero(buffer, sizeof(buffer)); if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0) { perror("RECV invitation message failed"); exit(1); } //printf("RECV [%d bytes]: invitation message\n", msg_size); output(buffer); char space; bzero(name, sizeof(name)); bzero(buffer, sizeof(buffer)); bzero(author, sizeof(author)); bzero(command, sizeof(command)); bzero(content, sizeof(content)); scanf("%5s%1c", command, &space); if ((msg_size = sendto(sock, command, strlen(command), 0, (struct sockaddr *)&client, sizeof(client))) < 0) { perror("SEND command failed"); exit(1); } //printf("SEND [%d bytes]: command '%s'\n", msg_size, path); if (!strcmp(command, ":exit")) { bzero(buffer, sizeof(buffer)); if ((msg_size = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0) // Receive the content of file { perror("RECV file or directory content failed"); exit(1); } //printf("RECV [%d bytes]: file or directory content\n", msg_size); output(buffer); break; } if (recv_report(sock) < 0) { puts("!No such command"); send_report(sock, SUCCESS); } if (!strcmp(command, "add")) { char str[SIZE_ARG]; fgets(name, sizeof(name), stdin); if (name[strlen(name) - 1] == '\n') name[strlen(name) - 1] = '\0'; if ((msg_size = sendto(sock, name, strlen(name), 0, (struct sockaddr *)&client, sizeof(client))) < 0) { perror("SEND command failed"); exit(1); } //printf("SEND [%d bytes]: title of article '%s'\n", msg_size, name); if (recv_report(sock) < 0) { puts("!Such file already exist"); send_report(sock, SUCCESS); } else { int length = sizeof(content) - sizeof(author) - sizeof(name); printf("Input author: "); fgets(author, sizeof(author), stdin); if (author[strlen(author) - 1] == '\n') author[strlen(author) - 1] = '\0'; printf("name's read: %s [%d bytes]\n", name, msg_size); printf("author's read: %s [%d bytes]\n", author, msg_size); puts("Put content:"); printf("[%d of %d] ", (strlen(content)+strlen(str)), length); while (fgets(str, sizeof(str), stdin) != NULL) { if (!strncmp(":end", str, strlen(":end"))) break; if ((strlen(content)+strlen(str)) > length) { puts("!Text size will not allow. Type less or :end"); bzero(str, strlen(str)); printf("[%d of %d] ", (strlen(content)+strlen(str)), length); //__fpurge(stdin); } strcat(content, str); bzero(str, strlen(str)); } if ((msg_size = sendto(sock, author, strlen(author), 0, (struct sockaddr *)&client, sizeof(client))) < 0) { perror("SEND author of article failed"); exit(1); } //printf("SEND [%d bytes]: author of article '%s'\n", msg_size, author); recv_report(sock); if ((msg_size = sendto(sock, content, strlen(content), 0, (struct sockaddr *)&client, sizeof(client))) < 0) { perror("SEND file content failed"); exit(1); } //printf("SEND [%d bytes]: file content '%s'\n", msg_size, content); if (recv_report(sock) < 0) puts("!Such file already exist"); send_report(sock, SUCCESS); } } gets(buffer); if (!strcmp(command, "open")) { strcat(path, buffer); if ((msg_size = sendto(sock, path, strlen(path), 0, (struct sockaddr *)&client, sizeof(client))) < 0) { perror("SEND full path to file failed"); exit(1); } printf("SEND [%d bytes]: full path to file '%s'\n", msg_size, path); } else if (!strcmp(command, "find")) { if ((msg_size = sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client))) < 0) { perror("SEND author to find failed"); exit(1); } //printf("SEND [%d bytes]: author to find '%s'\n", msg_size, buffer); } bzero(content, sizeof(content)); if ((msg_size = recvfrom(sock, content, sizeof(content), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0) // Receive the content of file { perror("RECV file or directory content failed"); exit(1); } //printf("RECV [%d bytes]: file or directory content\n", msg_size); output(content); send_report(sock, SUCCESS); } recv_msg(sock, content, sizeof(content), 0, (struct sockaddr *)&client, (socklen_t *)&len); /*int num = 0; char *ptr = &content[1]; char number[2]; while(1){ if ((msg_size = recvfrom(sock, content, sizeof(content), 0, (struct sockaddr *)&client, (socklen_t *)&len)) < 0) // Receive the content of file { perror("RECV file or directory content failed"); exit(1); } printf("RECV [%d bytes]: file or directory content\n", msg_size); memset(number, 0, sizeof(number)); strncpy(number, ptr, 2); printf("%d ", atoi(number)); output(content); if (num != atoi(number)) send_report(sock, UNSUCCESS); else send_report(sock, SUCCESS); num++; if (content[0] == '1') break; }*/ close(sock); return 0; }