Need Help with Winsock downloading (small errors)

I have this code here and it keeps getting small errors in what it downloads, which end up corrupting the files (.zip and .rar), it is also unable to get content from .asp pages. Can anyone give me some advice?
Compile line: g++ ws.cpp -lws2_32

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
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream>
#include <fstream>

using namespace std;


int main() {

char servername[40] = "members.myserver.com";
char filepath[40] = "/username/file.rar";
char filename[20] = "downloadedfile.rar";
char buff[512];
struct hostent *hp;
unsigned int addr;
struct sockaddr_in server;
int y;


WSAData wsaData;
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed: %d\n", iResult);
    return 1;
}



 SOCKET conn;
conn=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(conn==INVALID_SOCKET)
    return 0;


if(inet_addr(servername)==INADDR_NONE)
{
    hp=gethostbyname(servername);
}
else
{
    addr=inet_addr(servername);
    hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
}
if(hp==NULL)
{
    closesocket(conn);
    return 0;
}


server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
server.sin_family=AF_INET;
server.sin_port=htons(80);
if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
{
    closesocket(conn);
    return 0;
}

//possibly needs to be changed for other files?
sprintf(buff,"GET %s\r\n\r\n",filepath);
send(conn,buff,strlen(buff),0);


ofstream file;
file.open(filename);

while(y=recv(conn,buff,512,0))
{
	file << buff; //gets some slight errors
}


file.close();
closesocket(conn);


WSACleanup();

  return 0;
}


If anyone could give me information on how to get this working without those slight errros and for all file types I'd greatly appreciate it.

Thanks,
Wootski
Last edited on
Topic archived. No new replies allowed.