1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include <iostream> #include <fstream> #include <stdio.h> #include <winsock2.h> #pragma comment (lib, "ws2_32.lib")
#define BUF_SIZE 1024
int main() { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET servSock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.sin_family = PF_INET; sockAddr.sin_addr.s_addr = htonl(INADDR_ANY); sockAddr.sin_port = htons(3356); bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));
listen(servSock, 20);
SOCKADDR clntAddr; int nSize = sizeof(SOCKADDR); char buffer[BUF_SIZE] = { 0 }; char sbuffer[BUF_SIZE] = { 0 };
char ip[20] = { 0 }; struct hostent *phostinfo = gethostbyname(""); char *p = inet_ntoa(*((struct in_addr *)(*phostinfo->h_addr_list))); strncpy(ip, p, sizeof(ip) - 1); ip[sizeof(ip) - 1] = '\0'; printf("This is TCP file server(IP:%s)\n", ip); printf("waiting connect...\n");
while (1) { SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize); struct sockaddr_in *sock = (struct sockaddr_in*)&clntAddr; printf("client(IP:%s, PORT:%d)connect ok\n", inet_ntoa(sock->sin_addr), ntohs(sock->sin_port)); int strLen = recv(clntSock, buffer, BUF_SIZE, 0); FILE *pFile; pFile = fopen(buffer, "rb"); if (pFile) { fseek(pFile, 0, SEEK_END); int n = ftell(pFile); sprintf(sbuffer,"file:%s, size:%dKB\n", buffer, n / 1024); send(clntSock, sbuffer, BUF_SIZE, 0); recv(clntSock, buffer, BUF_SIZE, 0); if (*buffer == 'y') { fseek(pFile, 0, SEEK_SET); int len; while (1) { if((len = fread(&sbuffer, 1, BUF_SIZE, pFile)) && len > 0) { send(clntSock, sbuffer, len, 0); } else { printf("Download down!\n"); break; } } } else printf("Download Canceled!\n"); } else { sprintf(sbuffer, "file:%s not exist!!!\n", buffer); send(clntSock, sbuffer, BUF_SIZE, 0); }
closesocket(clntSock); memset(buffer, 0, BUF_SIZE); memset(sbuffer, 0, BUF_SIZE); }
closesocket(servSock);
WSACleanup();
return 0; }
|