Simple ping/ICMP for windows (IPv4)

Share your advanced PureBasic knowledge/code with the community.
User avatar
Lunasole
Addict
Addict
Posts: 1091
Joined: Mon Oct 26, 2015 2:55 am
Location: UA
Contact:

Simple ping/ICMP for windows (IPv4)

Post by Lunasole »

Hi. Recently I was porting yet another old app to PB (stuff to communicate with my routers), here is some PING procedure from it (so much shorter than original code ^^).

Code: Select all

EnableExplicit

; Send ICMP request to given IP
; RETURN:		value in ms on success, -1 else
Procedure Ping(IPv4.l, TimeOut=1000)
	Protected hFile = IcmpCreateFile_()
	Protected Res 
	Protected *Out.ICMP_ECHO_REPLY = AllocateMemory(SizeOf(ICMP_ECHO_REPLY) + 32)
	If IcmpSendEcho_(hFile, IPv4, "@Echo this stuff", 32, 0, *Out, MemorySize(*Out), TimeOut)  And *Out\Status = 0
		Res = *Out\RoundTripTime
	Else
		Res = -1
	EndIf
	IcmpCloseHandle_(hFile)
	FreeMemory(*Out)
	
	ProcedureReturn Res
EndProcedure


; ping google DNS server
Debug Ping(MakeIPAddress(8,8,8,8))
Last edited by Lunasole on Fri Nov 24, 2017 7:23 pm, edited 1 time in total.
"W̷i̷s̷h̷i̷n̷g o̷n a s̷t̷a̷r"
User avatar
RSBasic
Moderator
Moderator
Posts: 1218
Joined: Thu Dec 31, 2009 11:05 pm
Location: Gernsbach (Germany)
Contact:

Re: Simple ping/ICMP for windows (IPv4)

Post by RSBasic »

thx
Image
Image
User avatar
Lunasole
Addict
Addict
Posts: 1091
Joined: Mon Oct 26, 2015 2:55 am
Location: UA
Contact:

Re: Simple ping/ICMP for windows (IPv4)

Post by Lunasole »

Added ICMP_ECHO_REPLY status check (missed before)
"W̷i̷s̷h̷i̷n̷g o̷n a s̷t̷a̷r"
User avatar
skinkairewalker
Enthusiast
Enthusiast
Posts: 636
Joined: Fri Dec 04, 2015 9:26 pm

Re: Simple ping/ICMP for windows (IPv4)

Post by skinkairewalker »

if I ping using cmd with " -t " it stays for a long time without being interrupted, using this example, I always get the return -1, why does this happen?
Fruity
New User
New User
Posts: 5
Joined: Tue Aug 15, 2023 4:04 am

Re: Simple ping/ICMP for windows (IPv4)

Post by Fruity »

My dirty realization of ping in Linux

Note:
you need liboping to be installed (sudo apt install oping)
timeout.d in procedure in seconds

Code: Select all

ImportC "/lib/x86_64-linux-gnu/liboping.so.0"
	ping_construct()
	ping_host_add(*obj, *host)
	ping_send(*obj)
	ping_destroy(*obj)
	ping_setopt(*obj, opt.i, *val)
EndImport

Procedure.s ping(addr$)
	timeout.d = 1
	*host = Ascii(addr$ + Chr(0))
	*ping_Obj = ping_construct()
	If *ping_Obj
		host_add = ping_host_add(*ping_Obj, *host)
		setopt1 = ping_setopt(*ping_Obj, $01, @timeout)
		If host_add = 0
			time_start = ElapsedMilliseconds()
			ret = ping_send(*ping_Obj)
			time_end = ElapsedMilliseconds()
			ping_destroy(*ping_Obj)
			FreeMemory(*host)
			If ret > 0		
				ProcedureReturn Str(time_end - time_start)
			Else
				ProcedureReturn "fail"
			EndIf
		Else
			ping_destroy(*ping_Obj)			
		EndIf	
	EndIf
	FreeMemory(*host)
	ProcedureReturn "fail"
EndProcedure
Post Reply