Retrieving your public IP address

Post your FreeBASIC source, examples, tips and tricks here. Please don’t post code without including an explanation.
Post Reply
Vortex
Posts: 118
Joined: Sep 19, 2005 9:50

Retrieving your public IP address

Post by Vortex »

Hello,

A quick example to get your WAN IP address. Compile the source as console application.

Code: Select all

' Example of retrieving the WAN IP adress from an external source :
'
' GetPublicIP.exe http://whatismyip.akamai.com
' GetPublicIP.exe https://ipecho.net/plain
'
' If no command line option is specified then the application
' defaults to the address http://icanhazip.com

' Source code compiled with FreeBASIC Compiler - Version 1.09.0 (2021-12-31)

#include "windows.bi"
#include "win\wininet.bi"

Dim As Ulong argc = __fb_argc__
Dim As ZString Ptr Ptr argv = __fb_argv__
Dim As Integer i
Dim As HINTERNET hInt,hUrl
Dim As WINBOOL Irf
Dim As DWORD BuffSize
Dim As LPCSTR url
Dim As ZString * 128 App
Dim As ZString * 68 IpAddr
Dim As ZString Ptr Buffer=@IpAddr

If argc=1 Then
    
    url=Cast(ZString Ptr,@"http://icanhazip.com")
    
Else
    
    url=argv[1]
    
End If


GetModuleFileName(0,@App,128)

hInt=InternetOpen(@App,INTERNET_OPEN_TYPE_PRECONFIG,0,0,0)

If hInt=0 Then End 1

hUrl=InternetOpenUrl(hInt,url,0,0,0,0)


If hUrl=0 Then
    
    InternetCloseHandle(hInt)
    End 2
    
End If


Irf=InternetReadFile(hUrl,@IpAddr,64,@BuffSize)

InternetCloseHandle(hUrl)


If Irf=0 Then
    
    InternetCloseHandle(hInt)
    End 3
    
End If

*Cast(Ubyte Ptr,Buffer+BuffSize)=0


For i=1 To BuffSize
    
    If *Cast(Ubyte Ptr,Buffer)<32 Then *Cast(Ubyte Ptr,Buffer)=32
    
    Buffer+=1
    
Next i

Print IpAddr

InternetCloseHandle(hInt)

End 0
badidea
Posts: 2586
Joined: May 24, 2007 22:10
Location: The Netherlands

Re: Retrieving your public IP address

Post by badidea »

A linux version using 'curl':

Code: Select all

dim as string ipStr
open pipe "curl -s ifconfig.co" for input as #1
	line input #1, ipStr
close #1
print "My public ip-address: " & ipStr
Post Reply