Get Global IP address

Share your advanced PureBasic knowledge/code with the community.
Phantomas
User
User
Posts: 96
Joined: Wed Jul 01, 2009 12:59 pm

Get Global IP address

Post by Phantomas »

Hi, this is a simple procedure for get your global IP address.
Working with checkip.dyndns.org WEB server.

ProcedureReturn not used. Errors are handled in end of procedure (result = *).

Edit:
Thank to ts-soft for constant #PB_Ascii in PeekS().

Code: Select all

EnableExplicit

InitNetwork()

#getip_server = "checkip.dyndns.com"
#getip_server_host = "checkip.dyndns.org"
#getip_server_port = 80
#getip_server_protocol = "HTTP/1.0"
#getip_delay_part = 25

#getip_finder_id_left = "Current IP Address: "
#getip_finder_id_left_len = 20
#getip_finder_id_right = "</body></html>"
#getip_finder_id_right_len = 14

Procedure get_ip(buffer_size.i = 4096, time_for_update.i = 15000)
  Protected result.i = 0
  Protected connection_id.i = OpenNetworkConnection(#getip_server, #getip_server_port, #PB_Network_TCP)
  If connection_id <> 0
    Protected string_to_send_current_ip.s
    string_to_send_current_ip = "GET / " + #getip_server_protocol + #CRLF$
    string_to_send_current_ip + "Host: " + #getip_server_host + #CRLF$ + #CRLF$
    SendNetworkString(connection_id, string_to_send_current_ip)
    Protected time_current.i = ElapsedMilliseconds()
    Protected time_limit.i = time_current + time_for_update
    Repeat
      Select NetworkClientEvent(connection_id)
        Case #PB_NetworkEvent_Data
          Protected *memory_buffer = AllocateMemory(buffer_size)
          If *memory_buffer
            Repeat
              Protected break_from_main.i = 1
              Protected received_size.i = ReceiveNetworkData(connection_id, *memory_buffer, buffer_size)
              If received_size = -1
                CloseNetworkConnection(connection_id)
                result = 4
                Break
              Else
                Protected *memory_global
                If received_size = 0
                  CloseNetworkConnection(connection_id)
                  Debug PeekS(*memory_global)
                Else
                  Protected received_size_global.i
                  received_size_global + received_size
                  *memory_global = ReAllocateMemory(*memory_global, received_size_global)
                  If *memory_global
                    CopyMemory(*memory_buffer, *memory_global + (received_size_global - received_size), received_size)
                    CloseNetworkConnection(connection_id)
                    Break
                  Else
                    CloseNetworkConnection(connection_id)
                    result = 3
                    Break
                  EndIf                
                EndIf
              EndIf
              time_current = ElapsedMilliseconds()
              If time_current >= time_limit
                CloseNetworkConnection(connection_id)
                result = 2
                Break
              Else
                Delay(#getip_delay_part)
              EndIf
            ForEver
            FreeMemory(*memory_buffer)
              string_to_send_current_ip = PeekS(*memory_global, -1, #PB_Ascii)
              FreeMemory(*memory_global)
              string_to_send_current_ip = Mid(string_to_send_current_ip, FindString(string_to_send_current_ip, #getip_finder_id_left, 0) + #getip_finder_id_left_len, FindString(string_to_send_current_ip, #getip_finder_id_right, FindString(string_to_send_current_ip, #getip_finder_id_left, 0) + #getip_finder_id_left_len) - (FindString(string_to_send_current_ip, #getip_finder_id_left, 0) + #getip_finder_id_left_len))
              MessageRequester("Your global IP", "Your global IP is:" + #CRLF$ + string_to_send_current_ip)
              ProcedureReturn
            FreeMemory(*memory_global)
          Else
            CloseNetworkConnection(connection_id)
            result = 3
            Break
          EndIf
        Default
          time_current = ElapsedMilliseconds()
          If time_current >= time_limit
            CloseNetworkConnection(connection_id)
            result = 2
            Break
          Else
            Delay(#getip_delay_part)
          EndIf
      EndSelect
      If break_from_main = 1
        Break
      EndIf
    ForEver
  Else
    result = 1
  EndIf
  
  ;Errors
  If result = 1
    Debug "Can not connect to server"
  ElseIf result = 2
    Debug "Time out of get IP"
  ElseIf result = 3
    Debug "AllocateMemory error" ;Critical error!
  ElseIf result = 4
    Debug "Can not receive data from server"
  EndIf
  
EndProcedure

get_ip()
Last edited by Phantomas on Sun Dec 18, 2011 12:28 am, edited 2 times in total.
User avatar
ts-soft
Always Here
Always Here
Posts: 5756
Joined: Thu Jun 24, 2004 2:44 pm
Location: Berlin - Germany

Re: Get Global IP address

Post by ts-soft »

Small problem, doesn't work with unicode!
Change line 68 to:

Code: Select all

              string_to_send_current_ip = PeekS(*memory_global, -1, #PB_Ascii)
and it works.

Greetings - Thomas
PureBasic 5.73 | SpiderBasic 2.30 | Windows 10 Pro (x64) | Linux Mint 20.1 (x64)
Old bugs good, new bugs bad! Updates are evil: might fix old bugs and introduce no new ones.
Image
Phantomas
User
User
Posts: 96
Joined: Wed Jul 01, 2009 12:59 pm

Re: Get Global IP address

Post by Phantomas »

ts-soft, thanks! Updated...
User avatar
skywalk
Addict
Addict
Posts: 4219
Joined: Wed Dec 23, 2009 10:14 pm
Location: Boston, MA

Re: Get Global IP address

Post by skywalk »

Curious why you didn't use a simple GetHTTPHeader()?
Is it because no error checking?

Code: Select all

Procedure.s NL_ExtIP()
  Protected.s ExtIP$
  Protected.i Lpos, Rpos
  ExtIP$ = GetHTTPHeader("http://checkip.dyndns.org/")
  Lpos = FindString(ExtIP$, "IP Address:") + 11
  Rpos = FindString(ExtIP$, "<", Lpos) + 1
  ExtIP$ = Trim(Mid(ExtIP$, Lpos, Len(ExtIP$) - Rpos))
  ProcedureReturn ExtIP$
EndProcedure

;Debug GetHTTPHeader("http://checkip.dyndns.org/")
InitNetwork()
Debug NL_ExtIP()
The nice thing about standards is there are so many to choose from. ~ Andrew Tanenbaum
kvitaliy
Enthusiast
Enthusiast
Posts: 162
Joined: Mon May 10, 2010 4:02 pm

Re: Get Global IP address

Post by kvitaliy »

Who write shorter :?: :D

Code: Select all

If OpenWindow(0,0,0, 70, 30, "IP",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)
    WebGadget(0, -10, -15, 150, 45, "http://ip-whois.net/img_ip1.php")
  EndIf
  Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
  
Env
Enthusiast
Enthusiast
Posts: 151
Joined: Tue Apr 27, 2010 3:20 pm
Location: Wales, United Kingdom

Re: Get Global IP address

Post by Env »

kvitaliy wrote:Who write shorter :?: :D

Code: Select all

If OpenWindow(0,0,0, 70, 30, "IP",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)
    WebGadget(0, -10, -15, 150, 45, "http://ip-whois.net/img_ip1.php")
  EndIf
  Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
  
Hardly suitable for something where the IP is needed by the program for it to operate lol.

Nice code, Phantomas :) Thanks for sharing
Thanks!
Phantomas
User
User
Posts: 96
Joined: Wed Jul 01, 2009 12:59 pm

Re: Get Global IP address

Post by Phantomas »

Curious why you didn't use a simple GetHTTPHeader()?
Wow, this server (dyndns.org) always responds the current IP to any query. This is not correct on the server side (but comfortably). I did not know it. Because of what used GET (HTTP standard).
And yes, no timeout option, errors checking, etc.
User avatar
HeX0R
Addict
Addict
Posts: 1204
Joined: Mon Sep 20, 2004 7:12 am
Location: Hell

Re: Get Global IP address

Post by HeX0R »

kvitaliy wrote:Who write shorter :?: :D
Me?
kvitaliy
Enthusiast
Enthusiast
Posts: 162
Joined: Mon May 10, 2010 4:02 pm

Re: Get Global IP address

Post by kvitaliy »

HeX0R wrote:
kvitaliy wrote:Who write shorter :?: :D
Me?
Yes! Excellent!
:D
User avatar
ultralazor
Enthusiast
Enthusiast
Posts: 186
Joined: Sun Jun 27, 2010 9:00 am

Re: Get Global IP address

Post by ultralazor »

If you're connected directly to the modem device you can also use PnP to get it, if ony a sub device you have to use a service though. A simple HTTP get with TCP works fine, just disable compression and check for chunking.
so many ideas so little time..
smacker
User
User
Posts: 55
Joined: Thu Nov 06, 2014 7:18 pm

Re: Get Global IP address

Post by smacker »

Or you could do what i've been using, for public IPv4 or IPv6 address.

The PureBasic versions:

Code: Select all

Procedure.s GetPubIPv4Address()
  ; https://www.ipify.org/
  InitNetwork()
  *Buffer = ReceiveHTTPMemory("https://api.ipify.org?format=json")
  If *Buffer
    ParseJSON(0, PeekS(*Buffer, MemorySize(*Buffer), #PB_UTF8))
    FreeMemory(*Buffer)
    ip4addrs$ = GetJSONString(GetJSONMember(JSONValue(0), "ip"))
  EndIf
  
  ProcedureReturn Trim(ip4addrs$)
  
EndProcedure

Procedure.s GetPubIPv6Address()
  ; http://ip6.anysrc.net/json
  InitNetwork()
  *Buffer = ReceiveHTTPMemory("http://ip6.anysrc.net/json")
  If *Buffer
    ParseJSON(0, PeekS(*Buffer, MemorySize(*Buffer), #PB_UTF8))
    FreeMemory(*Buffer)
    ip6addrs$ = GetJSONString(GetJSONMember(JSONValue(0), "clientip"))
  EndIf
  
  ProcedureReturn Trim(ip6addrs$)
  
EndProcedure

Debug GetPubIPv4Address()
Debug GetPubIPv6Address()
The code above is from the http://www.ipify.org site and written by the owner of that site (I think, he has contributors also, so one of them may have written it - scroll down a little on his page and he has implementations for different coding platforms), credit to him. I used the same code for the IPv6 side also and just changed the site address. You can just about plug in any site that uses json.

If using Windows 10 and want to use powershell in Windows 10, here are some basic draft powershell versions that work for use in PureBasic:

Code: Select all


Procedure.b GetTestIfSiteIsUp(thesitetotest$) ; if site is down (or does not exist) PowerShell returns "Access down..."
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " wget " + thesitetotest$ + " | % {$_.StatusCode}","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
  
  If KeepOutCmd$ = "200" ; 200 = site OK
    siteupordown.b = #True 
  Else
    siteupordown.b = #False
  EndIf
  
  ProcedureReturn siteupordown

EndProcedure

Procedure.b GetValidateIPAddress(ipadrtoval$) 
  ; will validate IPv4 and IPv6
  ipadr$ = Chr(34) + Chr(39) + ipadrtoval$ + Chr(39) + Chr(34)
  
  OutCmd$ = ""
  KeepOutCmdA$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " [System.Net.IPAddress]::TryParse( " + ipadr$ + ", [ref] $NULL)","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmdA$ = KeepOutCmdA$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
  
  If Trim(KeepOutCmdA$) = "True"
    ProcedureReturn #True ; is a valid IPv4 or IPv6 address
  Else
    ProcedureReturn #False  ; is not a valid IPv4 or IPv6 address
  EndIf
  
EndProcedure


Procedure.s GetIPv4ipify()
  ; https://www.ipify.org/
  ; according to web site It "works flawlessly with both IPv4 and IPv6 addresses, 
  ; so no matter what sort of technology you're using, there won't be issues."
  ; but... the Ipv6 side is not working right now due to, from what I understand is, an IPv6 issue with Amazons domain (in which the site is hosted) 
 ; IPv6 supposedly due to be fixed by moving to another domain in about a month
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " Invoke-RestMethod https://api.ipify.org?format=json | Select ip","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
    
  ipinfoio$ = Trim(KeepOutCmd$)
  ipinfoio$ = RemoveString(ipinfoio$, "ip", #PB_String_NoCase, 1, 1)
  ipinfoio$ = Trim(RemoveString(ipinfoio$, "-", #PB_String_NoCase, 1))
  
  If CountString(ipinfoio$, ".") = 3 And Len(ipinfoio$) <= 15
    ProcedureReturn ipinfoio$
  Else
    ProcedureReturn "(No IPv4 Information resource 2)"
  EndIf
 
EndProcedure

Procedure.s Getipv4whatismyip()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " (Invoke-WebRequest http://ipv4.whatismyip.akamai.com/).Content","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
    
  ipv4whatismyipakamai$ = Trim(KeepOutCmd$)
      
  If CountString(ipv4whatismyipakamai$, ".") = 3 And Len(ipv4whatismyipakamai$) <= 15
    ProcedureReturn ipv4whatismyipakamai$
  Else
    ProcedureReturn "(No IPv4 Information resource 1)"
  EndIf
    
EndProcedure

Procedure.s GetIPv4ipinfo()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " Invoke-RestMethod http://ipinfo.io/json | Select -exp ip","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
    
  ipinfoio$ = Trim(KeepOutCmd$)
      
  If CountString(ipinfoio$, ".") = 3 And Len(ipinfoio$) <= 15
    ProcedureReturn ipinfoio$
  Else
    ProcedureReturn "(No IPv4 Information resource 2)"
  EndIf
 
EndProcedure

Procedure.s GetIPv4dnsomatic()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " (Invoke-WebRequest http://myip.dnsomatic.com/).Content","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
    
  myipdnsomatic$ = Trim(KeepOutCmd$)
      
  If CountString(myipdnsomatic$, ".") = 3 And Len(myipdnsomatic$) <= 15
    ProcedureReturn myipdnsomatic$
  Else
    ProcedureReturn "(No IPv4 Information resource 3)"
  EndIf
 
EndProcedure

Procedure.s GetIPv4icanhazip()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " (Invoke-WebRequest IPv4.Icanhazip.com).Content","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
  
  ipv4icanhazip$ = Trim(KeepOutCmd$) 
      
  If CountString(ipv4icanhazip$, ".") = 3 And Len(ipv4icanhazip$) <= 15
    ProcedureReturn ipv4icanhazip$
  Else
    ProcedureReturn "(No IPv4 Information resource 4)"
  EndIf
  
EndProcedure

Procedure.s GetIPv4myipdk()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " (Invoke-WebRequest http://ipv4.myip.dk/api/info/IPv4Address).Content","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
    
  ipv4myipdk$ = Trim(RemoveString(KeepOutCmd$, Chr(34), #PB_String_NoCase, 1))
      
  If CountString(ipv4myipdk$, ".") = 3 And Len(ipv4myipdk$) <= 15
    ProcedureReturn ipv4myipdk$
  Else
    ProcedureReturn "(No IPv4 Information resource 5)"
  EndIf
    
EndProcedure

Procedure.s GetIPv4AddressPublic()
  
  siteup.b = #True
  gotip4adr.b = #True
  
  ; https://www.ipify.org/ in case we need it and has json - both IPv4 and IPv6 addresses
  
  
  ; http://whatismyip.akamai.com/advanced
  ; http://ipecho.net/plain
  ; http://v4.ident.me/
  ; http://ident.me/
  ; http://ipv4.icanhazip.com/
  ; http://ipv6.icanhazip.com/
  
  ; http://api.ident.me/
  
;   ifcfg.me/all              all information
;   ifcfg.me/json             all information As json
;   ifcfg.me/rss              ip, host And isp As rss feed
;   ifcfg.me/?                this help
  
  ; http://checkip.amazonaws.com/
  
  ; http://ipof.in/json - has a blacklist check
  
  ; http://bot.whatismyipaddress.com/
  ; https://www.ipify.org/
  ; https://api.ipify.org/?format=json
  ; http://www.whatsmyip.website/api/json
  
;     bot.whatismyipaddress.com - Responds To IPv4 & IPv6 queries.
;     ipv4bot.whatismyipaddress.com - Responds To IPv4 queries only.
;     ipv6bot.whatismyipaddress.com - Responds To IPv6 queries only.
  
; http://ip.anysrc.net/json
; http://ip.anysrc.net/
  
  
; IPv4 - http://ip4.anysrc.net
; IPv6 - http://ip6.anysrc.net
; Auto detection - http://ip.anysrc.net
  

  
  If GetTestIfSiteIsUp("https://api.ipify.org?format=json") = #True
    pubipv4addr$ = GetIPv4ipify()
    If GetValidateIPAddress(pubipv4addr$) = #True
      ProcedureReturn pubipv4addr$
    Else
      gotip4adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://ipv4.whatismyip.akamai.com/") = #True And (gotip4adr = #False Or siteup = #False)) = #True
    pubipv4addr$ = Getipv4whatismyip()
    If GetValidateIPAddress(pubipv4addr$) = #True
      ProcedureReturn pubipv4addr$
    Else
      gotip4adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://ipinfo.io/json") = #True And (gotip4adr = #False Or siteup = #False)) = #True
    pubipv4addr$ = GetIPv4ipinfo()
    If GetValidateIPAddress(pubipv4addr$) = #True
      ProcedureReturn pubipv4addr$
    Else
      gotip4adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://myip.dnsomatic.com/") = #True And (gotip4adr = #False Or siteup = #False)) = #True
    pubipv4addr$ = GetIPv4dnsomatic()
    If GetValidateIPAddress(pubipv4addr$) = #True
      ProcedureReturn pubipv4addr$
    Else
      gotip4adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://ipv4.icanhazip.com/") = #True And (gotip4adr = #False Or siteup = #False)) = #True
    pubipv4addr$ = GetIPv4icanhazip()
    If GetValidateIPAddress(pubipv4addr$) = #True
      ProcedureReturn pubipv4addr$
    Else
      gotip4adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://ipv4.myip.dk/api/info/IPv4Address") = #True And (gotip4adr = #False Or siteup = #False)) = #True
    pubipv4addr$ = GetIPv4myipdk()
    If GetValidateIPAddress(pubipv4addr$) = #True
      ProcedureReturn pubipv4addr$
    Else
      gotip4adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(gotip4adr = #False Or siteup = #False) = #True
    ProcedureReturn "IPv4 Address resource not available."
  EndIf
  
EndProcedure

Procedure.s Getipv6whatismyip()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " (Invoke-WebRequest http://ipv6.whatismyip.akamai.com/).Content","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
    
  ipv6whatismyipakamai$ = Trim(KeepOutCmd$)
      
  If CountString(ipv6whatismyipakamai$, ":") > 0
    ProcedureReturn ipv6whatismyipakamai$
  Else
    ProcedureReturn "(No IPv6 Information resource 1)"
  EndIf
    
EndProcedure

Procedure.s GetIPv6icanhazip()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " (Invoke-WebRequest http://ipv6.icanhazip.com/).Content","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
  
  ipv6icanhazip$ = Trim(KeepOutCmd$) 
      
  If CountString(ipv6icanhazip$, ":") > 0
    ProcedureReturn ipv6icanhazip$
  Else
    ProcedureReturn "(No IPv6 Information resource 2)"
  EndIf
  
EndProcedure

Procedure.s GetIPv6ipv6test()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " (Invoke-WebRequest http://v6.ipv6-test.com/api/myip.php).Content","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
  
  ipv6test$ = Trim(KeepOutCmd$) 
      
  If CountString(ipv6test$, ":") > 0
    ProcedureReturn ipv6test$
  Else
    ProcedureReturn "(No IPv6 Information resource 3)"
  EndIf
  
EndProcedure

Procedure.s GetIPv6ipv6botwhatismyipaddress()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " (Invoke-WebRequest ipv6bot.whatismyipaddress.com).Content","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
  
  ipv6bot$ = Trim(KeepOutCmd$) 
      
  If CountString(ipv6bot$, ":") > 0
    ProcedureReturn ipv6bot$
  Else
    ProcedureReturn "(No IPv6 Information resource 4)"
  EndIf
  
EndProcedure

Procedure.s GetIPv6anysrc()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " Invoke-RestMethod http://ip6.anysrc.net/json | Select -exp clientip","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
  
  ipv6anysrc$ = Trim(KeepOutCmd$)
  
  If CountString(ipv6anysrc$, ":") > 0
    ProcedureReturn ipv6anysrc$
  Else
    ProcedureReturn "(No IPv6 Information resource 5)"
  EndIf
 
EndProcedure

Procedure.s GetIPv6myipdk()
  
  OutCmd$ = ""
  KeepOutCmd$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " (Invoke-WebRequest http://ipv6.myip.dk/api/info/IPv6Address).Content","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmd$ = KeepOutCmd$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
    
  ipv6myipdk$ = Trim(RemoveString(KeepOutCmd$, Chr(34), #PB_String_NoCase, 1))
      
  If CountString(ipv6myipdk$, ":") > 0
    ProcedureReturn ipv6myipdk$
  Else
    ProcedureReturn "(No IPv6 Information resource 6)"
  EndIf
    
EndProcedure

Procedure.s GetIPv6AddressPublic()
  
  siteup.b = #True
  gotip4adr.b = #True
  
  ; https://www.ipify.org/ in case we need it and has json - both IPv4 and IPv6 addresses
  ; http://ipv6.icanhazip.com/
  ; http://api.ident.me/
  ; IPv6 - http://ip6.anysrc.net
  ; http://ip6.anysrc.net/json
  ; http://ip6.anysrc.net/plain/clientip
  ; Auto detection - http://ip.anysrc.net
  
  If GetTestIfSiteIsUp("http://ipv6.whatismyip.akamai.com") = #True
    pubipv6addr$ = Getipv6whatismyip()
    If GetValidateIPAddress(pubipv6addr$) = #True
      ProcedureReturn pubipv6addr$
    Else
      gotip6adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://ipv6.icanhazip.com") = #True And (gotip6adr = #False Or siteup = #False)) = #True
    pubipv6addr$ = GetIPv6icanhazip()
    If GetValidateIPAddress(pubipv6addr$) = #True
      ProcedureReturn pubipv6addr$
    Else
      gotip6adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://v6.ipv6-test.com/api/myip.php") = #True And (gotip6adr = #False Or siteup = #False)) = #True
    pubipv6addr$ = GetIPv6ipv6test()
    If GetValidateIPAddress(pubipv6addr$) = #True
      ProcedureReturn pubipv6addr$
    Else
      gotip6adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://ipv6bot.whatismyipaddress.com/") = #True And (gotip6adr = #False Or siteup = #False)) = #True
    pubipv6addr$ = GetIPv6ipv6botwhatismyipaddress()
    If GetValidateIPAddress(pubipv6addr$) = #True
      ProcedureReturn pubipv6addr$
    Else
      gotip6adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://ip6.anysrc.net/json") = #True And (gotip6adr = #False Or siteup = #False)) = #True
    pubipv6addr$ = GetIPv6anysrc()
    If GetValidateIPAddress(pubipv6addr$) = #True
      ProcedureReturn pubipv6addr$
    Else
      gotip6adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(GetTestIfSiteIsUp("http://ipv6.myip.dk/api/info/IPv6Address") = #True And (gotip6adr = #False Or siteup = #False)) = #True
    pubipv6addr$ = GetIPv6myipdk()
    If GetValidateIPAddress(pubipv6addr$) = #True
      ProcedureReturn pubipv6addr$
    Else
      gotip6adr = #False
    EndIf
  Else
    siteup = #False
  EndIf
  
  If Bool(gotip6adr = #False Or siteup = #False) = #True
    ProcedureReturn "IPv6 Address resource not available or busy."
  EndIf
  
EndProcedure

Last edited by smacker on Thu Jan 05, 2017 1:15 pm, edited 3 times in total.
The world and human nature was screwed up before I was born. It's not my fault and I'm just stuck with trying to deal with the mess left behind, so don't blame me.
User avatar
blueb
Addict
Addict
Posts: 1116
Joined: Sat Apr 26, 2003 2:15 pm
Location: Cuernavaca, Mexico

Re: Get Global IP address

Post by blueb »

smacker...
Seems like lots of good stuff in there, but I can't find procedure GetValidateIPAddress()

location - inside procedure: GetIPv4AddressPublic()


blueb
- It was too lonely at the top.

System : PB 6.21(x64) and Win 11 Pro (x64)
Hardware: AMD Ryzen 9 5900X w/64 gigs Ram, AMD RX 6950 XT Graphics w/16gigs Mem
smacker
User
User
Posts: 55
Joined: Thu Nov 06, 2014 7:18 pm

Re: Get Global IP address

Post by smacker »

@blueb,

sorry 'bout that, got left out of the copy-n-paste to the post - the GetValidateIPAddress() procedure is:

Code: Select all

Procedure.b GetValidateIPAddress(ipadrtoval$) 
  ; will validate IPv4 and IPv6
  ipadr$ = Chr(34) + Chr(39) + ipadrtoval$ + Chr(39) + Chr(34)
  
  OutCmd$ = ""
  KeepOutCmdA$ = ""
  CmdPromptRun = RunProgram("powershell.exe", " [System.Net.IPAddress]::TryParse( " + ipadr$ + ", [ref] $NULL)","", #PB_Program_Hide|#PB_Program_Open|#PB_Program_Read)
  If CmdPromptRun
    While ProgramRunning(CmdPromptRun)
      OutCmd$=ReadProgramString(CmdPromptRun)
      KeepOutCmdA$ = KeepOutCmdA$ + OutCmd$
    Wend
    CloseProgram(CmdPromptRun)
  EndIf
  
  If Trim(KeepOutCmdA$) = "True"
    ProcedureReturn #True ; is a valid IPv4 or IPv6 address
  Else
    ProcedureReturn #False  ; is not a valid IPv4 or IPv6 address
  EndIf
  
EndProcedure
I also updated the other post to include it.

Note that TryParse returns true if it parsed the input successfully but that this does not necessarily mean the IP address fed to it is a valid IP address for use. Used for error trapping above, for example, if the sites API hiccups and returns nothing for the IP or returns an API error message of some sort, etc... so we move on to another site, because the site can be up and functioning but the API used to return the IP address could be experiencing an issue. For an IP address its basically determining whether or not the input string, e.g. 0.0.0.0, string can be converted to a valid IP address so its possible to have a non-usable IP address, e.g. 0.0.0.0, and TryParse will return true because it can convert the input to a valid IP address even if the IP is not one which is usable for networking or on the internet because, using the example 0.0.0.0, an address of 0.0.0.0 is still a valid IP address format wise. Works for IPv4 and IPv6, not perfect, but widely used and a lot simpler and easier than messing around with a regex, and its kinda fun being able to use a little .net in purebasic.
The world and human nature was screwed up before I was born. It's not my fault and I'm just stuck with trying to deal with the mess left behind, so don't blame me.
Post Reply