Jump to content

_GetIP() improved


FredAI
 Share

Recommended Posts

Just thought I'd share this one with you:

; #FUNCTION# ====================================================================================================================
; Name...........: _GetIP2
; Description ...: Get public IP address of a network/computer.
; Parameters ....: None
; Return values .: On Success - Returns the public IP Address
;                  On Failure - '0.0.0.0'  and sets @ERROR = 1
; Author ........: Larry/Ezzetabi & Jarvis Stubblefield & FredAI
; Remarks .......: Internet access.
; ===============================================================================================================================
Func _GetIP2()
    Local $aIp, $Text
    InetGet("http://checkip.dyndns.org/?rnd1="&Random(1,65536)&"&rnd2="&Random(1,65536),@TempDir&"\~ip.tmp")
    If @error Then
        InetGet("http://www.whatismyip.com/?rnd1="&Random(1,65536)&"&rnd2="&Random(1,65536),@TempDir&"\~ip.tmp")
        If @error Then Return SetError(1,0,'0.0.0.0')
    EndIf
    $Text = FileRead(@TempDir&"\~ip.tmp")
    FileDelete(@TempDir&"\~ip.tmp")
    $aIp = StringRegExp($Text,'\d{1,3}(\.\d{1,3}){3}',2)
    If Not @error Then Return $aIp[0]
    Return SetError(1,0,'0.0.0.0')
EndFunc   ;==>_GetIP
Link to comment
Share on other sites

This is how I did it >> (plus I use InetRead so no temporary file.) And the version is in the new AutoIt betas too.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

This is how I did it >> (plus I use InetRead so no temporary file.) And the version is in the new AutoIt betas too.

Great, guiness! Now I combined your function with my regular expression, which takes the IP from any page:

Func _GetIP2()
    Local $bRead = InetRead("http://checkip.dyndns.org/")
    If @error Then $bRead = InetRead("http://automation.whatismyip.com/n09230945.asp")
    If Not @error Then
        Local $aIp = StringRegExp(BinaryToString($bRead),'\d{1,3}(\.\d{1,3}){3}',2)
        If Not @error Then Return $aIp[0]
    EndIf
    Return SetError(1,0,'0.0.0.0')
EndFunc   ;==>_GetIP2

I don't want it showing -1 in my app if the internet is disconnected, so I changed the failure return value.

Link to comment
Share on other sites

You're welcome, great SRE too. And the -1 was because the original _GetIP() returned this.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Hmm that just failed on me and hung in a loop, so added a timeout and bit more error checking.

EDIT:

After running this in a loop It always returned in no more than 95 miliseconds

so changed timeout to reflect

Local $aresult = _IPFromIPConfig()
If Not IsArray($aresult) Then
    MsgBox(0, "Error", "Fail " & $aresult)
    Exit
EndIf

MsgBox(0, "Ip Address", "Ip " & @TAB & $aresult[0] & @CRLF & _
        "Subnet " & @TAB & $aresult[1] & @CRLF & _
        "Gateway " & @TAB & $aresult[2])

;===========================================================================
;Params $itimeout = [optional] Timeout in miliseconds if procedure hangs , Default = 250
;
;Sucess Returns an array
;[0] = IP
;[1] = Subnet Mask
;[2] = Default Gateway

;Failure Reurns an int
;-1 StderrRead timeout
;-2 StdoutRead timeout
;0 Run error
;1 StderrRead error
;2 StdoutRead error (no results)
;3 No Array error (StringSplit)
;===========================================================================

Func _IPFromIPConfig($itimeout = 250)
    Local $timer = TimerInit()
    Local $stderr, $stdout, $artn[3]
    Local $sipv4 = 'IPv4 Address'
    Local $ssubnet = 'Subnet Mask'
    Local $sdefault = 'Default Gateway'
    $pid = Run(@ComSpec & " /C " & "ipconfig", "", @SW_HIDE, 6)
    If @error Then Return 0
    Do
        If TimerDiff($timer) >= $itimeout Then
            ProcessClose($pid)
            Return -1
        EndIf
        $stderr &= StderrRead($pid)
    Until @error
    If $stderr Then Return 1
    Do
        If TimerDiff($timer) >= $itimeout Then
            ProcessClose($pid)
            Return -2
        EndIf
        $stdout &= StdoutRead($pid)
    Until @error
    If Not $stdout Then Return 2
    $asplit = StringSplit($stdout, @CR, 3)
    If Not IsArray($asplit) Then Return 3
    For $i = 0 To UBound($asplit) - 1
        If StringInStr($asplit[$i], $sipv4) Then
            $aip = StringSplit($asplit[$i], ":", 3)
            $artn[0] = StringStripWS($aip[1], 8)
        EndIf
        If StringInStr($asplit[$i], $ssubnet) Then
            $asub = StringSplit($asplit[$i], ":", 3)
            $artn[1] = StringStripWS($asub[1], 8)
        EndIf
        If StringInStr($asplit[$i], $sdefault) Then
            $adef = StringSplit($asplit[$i], ":", 3)
            $artn[2] = StringStripWS($adef[1], 8)
            ExitLoop
        EndIf
    Next
    Return $artn
EndFunc   ;==>_IPFromIPConfig
Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Link to comment
Share on other sites

  • 2 weeks later...

@JohnOne, your script doesn't work for me.

Anyway, I dont see why you're wasting your time with this. Isn't it much easier to use @IPAddress1?

The _GetIp() function returns not the network adapter IP, but the public (external) Ip. The one that is seen from the internet.

Hope it has been helpful.

Fred

Link to comment
Share on other sites

Yes, If I'm totally honest I just got enthralled in that, I was connected directly to my cable modem and was getting my External IP returned.

The blinkers went on and I just finished it.

I suppose its still ok for default gateway.

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

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...