function DownloadFileFromNet(sURL, sDestination:
String): Boolean;
var
hSocket, hFile: THandle;
WSData: TWSAData;
SockAddr: TSockAddr;
HostEnt: PHostEnt;
IPAddress, sGet, Location, Site,
URL:
String;
i, intReceived, intPosition: Integer;
lpNumberOfBytesWritten: DWORD;
lpBuffer:
Array[0..1024]
of Char;
const
szGet = '
GET %s HTTP/1.1' + lpEnter +
'
Host: %s' + lpEnter +
'
Connection: close' + lpEnter + lpEnter;
begin
Result := False;
Location := Split(sURL, '
://', 2);
Site := ExtractURLSite(Location);
URL := ExtractURLPath(Location);
if FileExists(sDestination)
then
DeleteFile(PChar(sDestination));
hFile := CreateFile(PChar(sDestination), GENERIC_WRITE, FILE_SHARE_WRITE,
nil, CREATE_NEW, 0, 0);
WSAStartup($0101, WSData);
hSocket := Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
HostEnt := GetHostByName(PChar(Site));
if HostEnt <>
nil then
begin
for i := 0
to HostEnt^.h_length -1
do
IPAddress := IPAddress + IntToStr(Ord(HostEnt.h_addr_list^[i])) + '
.';
SetLength(IPAddress, Length(IPAddress) -1);
end;
SockAddr.sin_family := AF_INET;
SockAddr.sin_port := htons(80);
SockAddr.sin_addr.S_addr := inet_addr(PChar(IpAddress));
if connect(hSocket, SockAddr, sizeof(SockAddr)) = SOCKET_ERROR
then
Exit;
sGet := Format(szGet, [
URL, Site]);
ZeroMemory(@lpBuffer, sizeof(lpBuffer));
if send(hSocket, sGet[1], Length(sGet), 0) = SOCKET_ERROR
then
Exit;
repeat
ZeroMemory(@lpBuffer, sizeof(lpBuffer));
intReceived := recv(hSocket, lpBuffer, sizeof(lpBuffer), 0);
if (Copy(lpBuffer, 0, 15) = '
HTTP/1.1 200 OK')
or
(Copy(lpBuffer, 0, 15) = '
HTTP/1.0 200 OK')
then
begin
intPosition := Pos(lpEnter + lpEnter, lpBuffer) +3;
WriteFile(hFile, lpBuffer[intPosition], intReceived - intPosition, lpNumberOfBytesWritten,
nil);
continue;
end else
WriteFile(hFile, lpBuffer, intReceived, lpNumberOfBytesWritten,
nil);
until (intReceived = SOCKET_ERROR)
or (intReceived = 0);
CloseSocket(hSocket);
CloseHandle(hFile);
Result := True;
end;