发送端(客户端)
1 #include <iostream> 2 #include <winsock2.h> 3 #include <Ws2tcpip.h> 4 #include <fstream> 5 using namespace std; 6 7 #pragma comment(lib, "ws2_32.lib") 8 9 struct FileHeader 10 { 11 12 char m_szFileName[MAX_PATH];//windows下,全文件名的字符长度是有限制的,众所周知,是MAX_PATH,260 13 int m_nFileSize; 14 15 }; 16 17 int main() 18 { 19 WORD wVersionRequested; 20 WSADATA wsaData; 21 int err; 22 23 24 wVersionRequested = MAKEWORD(2, 2); 25 26 err = WSAStartup(wVersionRequested, &wsaData); 27 if (err != 0) { 28 29 printf("WSAStartup failed with error: %d ", err); 30 return 1; 31 } 32 33 34 if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { 35 36 printf("Could not find a usable version of Winsock.dll "); 37 WSACleanup(); 38 return 1; 39 } 40 else 41 printf("The Winsock 2.2 dll was found okay "); 42 43 SOCKET sockClient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); 44 if(INVALID_SOCKET == sockClient) 45 { 46 WSACleanup(); 47 return 1; 48 } 49 cout<<"请输入服务器iP"<<endl; 50 char szip[100] = {0}; 51 cin>>szip; 52 sockaddr_in addr; 53 54 55 addr.sin_addr.S_un.S_addr=inet_addr("192.168.202.1"); 56 57 addr.sin_family = AF_INET; 58 //addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.251"); 59 addr.sin_port = htons(1234); 60 61 if(SOCKET_ERROR == connect(sockClient,(const sockaddr*)&addr,sizeof(addr))) 62 { 63 WSACleanup(); 64 closesocket(sockClient); 65 return 1; 66 } 67 68 char szFilePath[MAX_PATH] = {0}; 69 char *ptemp = szFilePath; 70 char szResult[4] = {0};//是,否 71 char szContent[1024] = {0};//文件内容 72 //文件头 73 //文件名,文件大小 74 FileHeader fh; 75 cout<<"请输入要传输的文件"<<endl; 76 cin>>szFilePath; 77 78 //获得文件名 79 while(*ptemp++ != '