Jump to content

How to save file via TCP?


Recommended Posts

Hi all,

I am trying to get source of some file, and save it to hard drive, but it seems that i need some sort of converting (to/from binary?)...

Here is what i am trying:

Global Const $HTTPUSERAGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0"
Global Const $HTTP_TCP_PORT = 80

$sFileContent = _HTTPGetSource("creator-lab.ucoz.ru", "/avatar/Scorpion_animated_64X64.gif")
$sFileContent = StringStripWS(StringTrimLeft($sFileContent, StringInStr($sFileContent, @CRLF & @CRLF)), 1)

$hFile = FileOpen(@ScriptDir & "\Scorpion_animated_64X64.gif", 2)
FileWrite($hFile, $sFileContent)
FileClose($hFile)

Func _HTTPGetSource($sHost, $sPage)
    Local $sRecv = '', $sCurrentLine
    Local $iSocket = _HTTPConnect($sHost)
    
    _HTTPGet($sHost, $sPage, $iSocket)
    If @error Then Return SetError(1, 0, '')
    
    While 1
        $sCurrentLine = TCPRecv($iSocket, 1024)
        If @error <> 0 Then ExitLoop
        If $sCurrentLine <> '' Then $sRecv &= $sCurrentLine
    WEnd
    
    TCPCloseSocket($iSocket)
    TCPShutdown()
    
    Return $sRecv
EndFunc

Func _HTTPConnect($sHost)
    TCPStartup()
    
    Local $sName_To_IP = TCPNameToIP($sHost)
    Local $iSocket = TCPConnect($sName_To_IP, $HTTP_TCP_PORT)
    
    If $iSocket = -1 Then
        TCPCloseSocket($iSocket)
        Return SetError(1, 0, "")
    EndIf
    
    Return $iSocket
EndFunc

Func _HTTPGet($sHost, $sPage, $iSocket)
    Local $sCommand = "GET " & $sPage & " HTTP/1.1" & @CRLF
    $sCommand &= "Host: " & $sHost & @CRLF
    $sCommand &= "User-Agent: " & $HTTPUSERAGENT & @CRLF
    $sCommand &= "Connection: close" & @CRLF & @CRLF
    
    Local $iBytesSent = TCPSend($iSocket, $sCommand)
    If $iBytesSent = 0 Then Return SetError(1, @error, 0)
    Return $iBytesSent
EndFunc

If i do the same with text file, all ok, the file include correct data, but with files such as images/executables, i get unworking file.

And also i wondernig, is there a way to get source without the header? i mean using TCP...

P.S

And where i can read about "commands" (data parameter) that can be sent via TCPSend?

Thanks.

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Took me a while to get it to work because the _HexToString function continued to error out and return an incorrect value. It turns out, the hex string has 9 "0x" prefixes located in the hex string in what seems to be random locations for absolutely no apparent reason other than to throw an error in the _HexToString function. I say this because there should only be a "0x" prefix at the very beginning of the hex string. After finding this, I had the hex string completely stripped of all "0x" prefixes. I don't know what the other 8 prefixes were doing in the middle of the hex string, but they were there.

In addition to that, you also need to open the file for binary write using the 2+16 flag. 2 for erase previous contents file write and 16 for binary mode.

#include <String.au3>
Global Const $HTTPUSERAGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0"
Global Const $HTTP_TCP_PORT = 80

$sFileContent = _HTTPGetSource("creator-lab.ucoz.ru", "/avatar/Scorpion_animated_64X64.gif")
$sFileContent = StringStripWS(StringTrimLeft($sFileContent, StringInStr($sFileContent, @CRLF & @CRLF)), 1)

$sFileContent = StringReplace($sFileContent,"0x","");Remove all the 0x hex prefixes from the string
ConsoleWrite("Number of replacements="&@extended&@LF);Report how many prefixes were removed from the string

$hFile = FileOpen(@ScriptDir & "\Scorpion_animated_64X64.gif", 2 + 16); Open for erase previous contents writing and binary
FileWrite($hFile, _HexToString($sFileContent));Convert the hex to a string and then write it to file
FileClose($hFile)

Func _HTTPGetSource($sHost, $sPage)
    Local $sRecv = '', $sCurrentLine
    Local $iSocket = _HTTPConnect($sHost)
   
    _HTTPGet($sHost, $sPage, $iSocket)
    If @error Then Return SetError(1, 0, '')
   
    While 1
        $sCurrentLine = TCPRecv($iSocket, 1024)
        If @error <> 0 Then ExitLoop
        If $sCurrentLine <> '' Then $sRecv &= $sCurrentLine
    WEnd
   
    TCPCloseSocket($iSocket)
    TCPShutdown()
   
    Return $sRecv
EndFunc

Func _HTTPConnect($sHost)
    TCPStartup()
   
    Local $sName_To_IP = TCPNameToIP($sHost)
    Local $iSocket = TCPConnect($sName_To_IP, $HTTP_TCP_PORT)
   
    If $iSocket = -1 Then
        TCPCloseSocket($iSocket)
        Return SetError(1, 0, "")
    EndIf
   
    Return $iSocket
EndFunc

Func _HTTPGet($sHost, $sPage, $iSocket)
    Local $sCommand = "GET " & $sPage & " HTTP/1.1" & @CRLF
    $sCommand &= "Host: " & $sHost & @CRLF
    $sCommand &= "User-Agent: " & $HTTPUSERAGENT & @CRLF
    $sCommand &= "Connection: close" & @CRLF & @CRLF
   
    Local $iBytesSent = TCPSend($iSocket, $sCommand)
    If $iBytesSent = 0 Then Return SetError(1, @error, 0)
    Return $iBytesSent
EndFunc

Once those changes were made, the image was written to the file successfully.

- The Kandie Man ;-)

"So man has sown the wind and reaped the world. Perhaps in the next few hours there will no remembrance of the past and no hope for the future that might have been." & _"All the works of man will be consumed in the great fire after which he was created." & _"And if there is a future for man, insensitive as he is, proud and defiant in his pursuit of power, let him resolve to live it lovingly, for he knows well how to do so." & _"Then he may say once more, 'Truly the light is sweet, and what a pleasant thing it is for the eyes to see the sun.'" - The Day the Earth Caught Fire

Link to comment
Share on other sites

It works! thanks!

But with executable still not working :) ... here is what i am testing:

http://creator-lab.ucoz.ru/Testing_Zone/Tester_Exe.exe

http://creator-lab.ucoz.ru/Testing_Zone/Tester_zip.zip

http://creator-lab.ucoz.ru/Testing_Zone/Tester_au3.au3

Only zip file is saved correctly, exe and au3 include incorrect data...

I think there is need to find a universal way to convert... but i have no idea in what direction i need to search :P

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...