IP Renew - a program to help and report

Everything else that doesn't fall into one of the other PB categories.
oldefoxx
Enthusiast
Enthusiast
Posts: 532
Joined: Fri Jul 25, 2003 11:24 pm

IP Renew - a program to help and report

Post by oldefoxx »

The included code lets you use a batch process to process IPCONFIG and ARP commands to refresh your network connections and report the resulting configuration by putting the results in a temporary file, which can then be processed in your code.

Using a batch file proved to provide more stability to this process than could be obtained by calling the separate statements using a RunProgram() for each, even with the flags set to 3 during each call. In particular, the ARP redirect command was severely impacted during the RunProgram() call, a problem not found in the manual call or when used as part of a batch process. This might be classified as a bug.

Code: Select all


;IPRenew
;by Donald R. Darden

;Creates a batch file and runs it to refresh IP
;links and copy the results into a temporary file
;that can then be processed:  C:\IP_Info.tmp.

;Attempts to use RunProgram() and make these calls
;directly worked, but the efforts to redirect the
;output using ">" and ">>" to the c:\IP_Info.tmp
;file were not as consistent as they should of been,
;especially with the ARP command.  By creating and
;running a batch file instead, these problems were
;overcome.and good results obtained.  


OpenConsole()
ConsoleColor(15,1)
ClearConsole()
PrintN("Please wait a moment while connections are refreshed...")
CreateFile(1,"c:\IPRenew.bat")
WriteStringN("@echo off")
WriteStringN("arp -d")
WriteStringN("ipconfig /flushdns")
WriteStringN("ipconfig /release")
WriteStringN("ipconfig /renew")
WriteStringN("ipconfig .all")
WriteStringN("ipconfig /all > c:\IP_Info.tmp")
WriteStringN("arp -a >> c:\IP_Info.tmp")
CloseFile(1)
If RunProgram("c:\IPRenew.bat","","c:\",3)
  If ReadFile(1,"c:\IP_Info.tmp")
    While Eof(1)=0
      a$=ReadString()
      If Trim(a$)>""
        b.l=0
        While b<Len(a$)
          c.l=FindString(a$,Chr(9),b+1)
          If c=0
            c=Len(a$)+1
          EndIf
          Print(Mid(a$,b+1,c-b-1)+" ")
          b=c
        Wend
        PrintN("")
      EndIf
    Wend
    CloseFile(1)
  EndIf
EndIf
DeleteFile("c:\IPRenew.bat")
Repeat
Until Inkey()>""
CloseConsole()
End

has-been wanna-be (You may not agree with what I say, but it will make you think).
oldefoxx
Enthusiast
Enthusiast
Posts: 532
Joined: Fri Jul 25, 2003 11:24 pm

IPRenew - Extended Version

Post by oldefoxx »

Adds tool for finding IP address in text fields, and listing these at the end of the program. Also added a ping -a to get the PC's URL.

Code: Select all


;IPRenew
;by Donald R. Darden

;Creates a batch file and runs it to refresh IP
;links and copy the results into a temporary file
;that can then be processed:  C:\IP_Info.tmp.

;Attempts to use RunProgram() and make these calls
;directly worked, but the efforts to redirect the
;output using ">" and ">>" to the c:\IP_Info.tmp
;file were not as consistent as they should of been,
;especially with the ARP command.  By creating and
;running a batch file instead, these problems were
;overcome.and good results obtained.  
Dim txt$(100)
Dim ip$(100)
Dim ofs.l(100)
Global idx.l

OpenConsole()
ConsoleColor(15,1)
ClearConsole()
PrintN("Please wait a few moments while connections are refreshed...")
CreateFile(1,"c:\IPRenew.bat")
WriteStringN("@echo off")
WriteStringN("arp -d")
WriteStringN("ipconfig /flushdns")
WriteStringN("ipconfig /release")
WriteStringN("ipconfig /renew")
WriteStringN("ipconfig .all")
WriteStringN("ipconfig /all > c:\IP_Info.tmp")
WriteStringN("arp -a >> c:\IP_Info.tmp")
WriteStringN("ping -a 127.0.0.1 >> c:\IP_Info.tmp")
CloseFile(1)
If RunProgram("c:\IPRenew.bat","","c:\",3)
  If ReadFile(1,"c:\IP_Info.tmp")
    bb$=""
    While Eof(1)=0
      a$=ReadString()
      b$=""
      a.l=FindString(a$,"Reply from",1)
      If a
        bb$=Mid(a$,a,Len(b$)-a)
        a$=Left(a$,a-1)
      EndIf
      If Trim(a$)>""
        b.l=0
        While b<Len(a$)
          c.l=FindString(a$,Chr(9),b+1)
          If c=0:c=Len(a$)+1:EndIf
          b$=b$+Mid(a$,b+1,c-b-1)+" "
          b=c
        Wend
        b$=RTrim(b$)
        PrintN(b$)
        a=0
        Repeat
          e.l=FindString(b$,".",a+1)
          a=e
          b.l=FindString(b$,".",a+1)
          c.l=FindString(b$,".",b+1)
          If c>a 
            If FindString(Mid(b$,a,c-a)," ",2)
              Goto BadIP
            EndIf
            e=a-3
            If e<1:e=1:EndIf
            d.l=0
            For b=e To c+3
              c$=Mid(b$,b,1)
              Select c$
              Case ""
                Goto GoodIP
              Case " "
spaced:              
                If d>0
                  If b>c:Goto GoodIP:EndIf
                EndIf  
                d=-1
              Case Chr(9)
                Goto spaced
              Case "0"
                If d<1:d=b:EndIf
              Case "1"
                If d<1:d=b:EndIf
              Case "2"
                If d<1:d=b:EndIf
              Case "3"
                If d<1:d=b:EndIf
              Case "4"
                If d<1:d=b:EndIf
              Case "5"
                If d<1:d=b:EndIf
              Case "6"
                If d<1:d=b:EndIf
              Case "7"
                If d<1:d=b:EndIf
              Case "8"
                If d<1:d=b:EndIf
              Case "9"
                If d<1:d=b:EndIf
              Case "."
                If d=0:Goto BadIP:EndIf
              Case "["
                Goto spaced
              Case "]"
                Goto spaced
              Case "("
                Goto spaced
              Case ")"
                Goto spaced
              Case Chr(34)
                Goto spaced
              Case "'"
                Goto spaced
              Default
                If d:Goto BadIP:EndIf
              EndSelect
            Next
          Else
            Goto BadIP    
          EndIf
GoodIP:
          If d>0
            idx=idx+1
            txt$(idx)=b$
            ip$(idx)=Mid(b$,d,b-d)
            ofs(idx)=d
            a=FindString(b$,".",c+1)-1
          EndIf
BadIP:
        Until a<=0         
      EndIf
    Wend
    CloseFile(1)
    Print("Press any key To continue...")
    Repeat:Until Inkey()>""
  EndIf
EndIf
DeleteFile("c:\IPRenew.bat")
ClearConsole()
PrintN("Extracted IP Addresses:")
For a=1 To idx
  ConsoleLocate(1,a+1)
  ConsoleColor(15,1)
  Print(Left(txt$(a),ofs(a)-1))
  ConsoleLocate(ofs(a),a+1)
  ConsoleColor(15,4)
  Print(ip$(a))
  ConsoleLocate(ofs(a)+Len(ip$(a)),a+1)
  ConsoleColor(15,1)
  a$=Mid(txt$(a),ofs(a)+Len(ip$(a)),Len(txt$(a)))
  PrintN(a$)
Next
PrintN("")
Print("Press any key to end...")
Repeat:Until Inkey()>""
CloseConsole()
End

has-been wanna-be (You may not agree with what I say, but it will make you think).
oldefoxx
Enthusiast
Enthusiast
Posts: 532
Joined: Fri Jul 25, 2003 11:24 pm

Adding NetStat Results to the Mix

Post by oldefoxx »

After reading about some of the things that you can do with NetStat at the command prompt, I decided to add some commands to the Mix. Here is the updated file:

Code: Select all

;IPRenew
;by Donald R. Darden

;Creates a batch file and runs it to refresh IP
;links and copy the results into a temporary file
;that can then be processed:  C:\IP_Info.tmp.

;Attempts to use RunProgram() and make these calls
;directly worked, but the efforts to redirect the
;output using ">" and ">>" to the c:\IP_Info.tmp
;file were not as consistent as they should of been,
;especially with the ARP command.  By creating and
;running a batch file instead, these problems were
;overcome.and good results obtained.  


OpenConsole()
ConsoleColor(15,1)
ClearConsole()
PrintN("Please wait a moment while connections are refreshed...")
CreateFile(1,"c:\IPRenew.bat")
WriteStringN("@echo off")
WriteStringN("arp -d")
WriteStringN("ipconfig /flushdns")
WriteStringN("ipconfig /release")
WriteStringN("ipconfig /renew")
WriteStringN("ipconfig .all")
WriteStringN("ipconfig /all > c:\IP_Info.tmp")
WriteStringN("arp -a >> c:\IP_Info.tmp")
WriteStringN("netstat -a >> c:\IP_Info.tmp")
WriteStringN("netstat -e ?? c:\IP_Info.tmp")
WriteStringN("netstat -n >> c:\IP_Info.tmp")
WriteStringN("netstat -r >> c:\IP_Info.tmp")
WriteStringN("netstat -s >> c:\IP_Info.tmp")
CloseFile(1)
If RunProgram("c:\IPRenew.bat","","c:\",3)
  If ReadFile(1,"c:\IP_Info.tmp")
    While Eof(1)=0
      a$=ReadString()
      If Trim(a$)>""
        b.l=0
        While b<Len(a$)
          c.l=FindString(a$,Chr(9),b+1)
          If c=0
            c=Len(a$)+1
          EndIf
          Print(Mid(a$,b+1,c-b-1)+" ")
          b=c
        Wend
        PrintN("")
      EndIf
    Wend
    CloseFile(1)
  EndIf
EndIf
DeleteFile("c:\IPRenew.bat")
Repeat
Until Inkey()>""
CloseConsole()
End
has-been wanna-be (You may not agree with what I say, but it will make you think).
TerryHough
Enthusiast
Enthusiast
Posts: 781
Joined: Fri Apr 25, 2003 6:51 pm
Location: NC, USA
Contact:

Post by TerryHough »

:D
Glad to see someone besides me realizes that DOS batch files can be
used for productive tasks. At least up through Win9x and ME.

I see in one of your examples the use of the PING.EXE program via
your created batch file.

Calling these DOS based programs from inside a GUI program works
but can sometimes be very awkward for less than experience computer
users to understand what is going on. The tasks shown on the monitor
at the end of the DOS based operation may or may not be the one
expected, and as you have experienced, capturing the results can be
very frustrating and difficult.

I recently ran into that while trying to use PING.EXE myself. So, I
searched a bit on the forum, asked a question, and did some coding.
The result is a completely GUI version of PING that I called PING2.

It allows me to completely replace the M$ PING.EXE for my purposes.
Here are a couple of screen shots:

Image

Image

And here is the code.

Code: Select all

;PING2 - Sep 08, 2003 - Terry Hough based on work by 
;  1) PING by Siegfried Rings (known as the 'CodeGuru' ),
;  2) URLtoIPAddress by PWS32 (from German forum), and
;  3) LocalHostName by AlphaSnd (Fred) on main forum.
;
;PING2 is a Windows GUI version of the DOS based PING available on 
;Windows systems usually located as \WINDOWS\PING.EXE. PING2 add a 
;Windows interface and slightly extends the capabilites, yet remains
;about 50 percent smaller.
;
;Plan to add an Error code interpretation in the future as time permits.
; 
Structure HOSTENT 
h_name.l 
h_aliases.l 
h_addrtype.w 
h_length.w 
h_addr_list.l 
EndStructure 

Dim bytes.w(4)
Dim PingResult.w(6)
Dim ttls.b(4)
;
Global PacketCount.w
Global RecdPackets.w
Global LostPackets.w
Global LostPercent.f
Global CheckOut.s
Global Message.s
Global Command$.s
Global TheIPAddress.s
Global MsgLen.b
Global AvgTrip.f     : AvgTrip = 0
Global MaxTrip.w     : MaxTrip = 0
Global MinTrip.w     : MinTrip = 0
;
Declare lngNewAddress(strAdd.s)
Declare Ping(strAdd.s)
Declare GetIPbyName(NameIP.s)
Declare Minimum(a.w,b1.w)
Declare Maximum(a.w,b1.w)
Declare GoDoIt(CheckStr.s)
;
Command$ = ""
Command$ = LCase(ProgramParameter())
If Len(Command$)>0
  If Asc(Mid(Command$,1,1)) < 48 Or Asc(Mid(Command$,1,1)) > 57
    URL$ = Command$                     ; This is a URL instead of an IP Address, eg. www.google.com
    IP$ = ""
  Else
    IP$ = Command$                      ; This is an IP Address in a string
    URL$ = ""
  EndIf   
EndIf

If OpenWindow(0, 1, 1, 600, 409, #PB_Window_WindowCentered|#PB_Window_SystemMenu | #PB_Window_SizeGadget | #PB_Window_TitleBar , "PING2")
  HideWindow(0,1)
  CreateGadgetList(WindowID())
  TextGadget(1, 10, 30,160, 20, "Enter a URL", #PB_Text_Right)
  StringGadget(2, 180, 30, 300, 20, URL$)
  TextGadget(1, 490, 30, 60, 20, "or")
  TextGadget(1, 10, 60,160, 20, "Enter an IP Address", #PB_Text_Right)
  IPAddressGadget(4, 180, 60, 150, 20) 
  If Len(IP$)
    Field1.w = Val(StringField(IP$, 1, "."))
    Field2.w = Val(StringField(IP$, 2, "."))
    Field3.w = Val(StringField(IP$, 3, "."))
    Field4.w = Val(StringField(IP$, 4, "."))
    SetGadgetState(4,MakeIPAddress(Field1,Field2,Field3,Field4))
  EndIf   
  ButtonGadget(6, 270, 90, 60, 30, "Proceed")
  ActivateGadget(2) 
  While WindowEvent():Wend
EndIf
  ; ---------------- This is the main processing loop ----------------------
  If Len(Command$)
    GoDoIt(CheckOut)
    End                                 ; End it if running with a command tail
  EndIf 

  HideWindow(0,0)    
  Repeat
    EventID = WaitWindowEvent()
     
    ; ------------------ Process the gadget events -------------------------
    If EventID = #PB_EventGadget
      Select EventGadgetID()
        Case 6    ; Proceed button chosen
          GoDoIt(CheckOut)
          
      EndSelect
    EndIf   
      
    If EventID =  #WM_CLOSE ;  #PB_EventCloseWindow
      Quit = 1      
    EndIf

  ; ------------ Insure changes are saved when quit received ---------------
  If Quit = 1
  EndIf  

  Until Quit = 1
  ; -------------------End of the main processing loop ---------------------

; ---------------------------------------------------------------------
; End of Main program code
; ---------------------------------------------------------------------

; Procedures
Procedure lngNewAddress(strAdd.s)
  sDummy.s=strAdd
  Position = FindString(sDummy, ".",1)
  If Position>0
    A1=Val(Left(sDummy,Position-1))
    sDummy=Right(Sdummy,Len(Sdummy)-Position)
    Position = FindString(sDummy, ".",1)
    If Position>0
      A2=Val(Left(sDummy,Position-1))
      sDummy=Right(Sdummy,Len(Sdummy)-Position)
      Position = FindString(sDummy, ".",1)
      If Position>0
        A3=Val(Left(sDummy,Position-1))
        sDummy=Right(Sdummy,Len(Sdummy)-Position)
        A4=Val(sDummy)
        Dummy.l=0
        PokeB(@Dummy,A1)
        PokeB(@Dummy+1,A2)
        PokeB(@Dummy+2,A3)
        PokeB(@Dummy+3,A4)
        ProcedureReturn Dummy
      EndIf
    EndIf
  EndIf
EndProcedure

Procedure Ping(strAdd.s)
  #PING_TIMEOUT = 255
  lngHPort.l
  lngDAddress.l
  strMessage.s
  lngResult.l
  ECHO.ICMP_ECHO_REPLY
  strMessage.s = "Echo This Information Back To Me"
  MsgLen = Len(strMessage)
  Message.s="Pinging "+CheckOut
  If Asc(Mid(strAdd,1,1)) < 48 Or Asc(Mid(strAdd,1,1)) > 57
    ; This is a URL instead of an IP Address, eg. www.google.com
    GetIPbyName(strAdd)                 ; Get the IP Address for the URL
    If Asc(Mid(TheIPAddress,1,1)) < 58  ; If successful, convert to numeric
      lngDAddress = lngNewAddress(TheIPAddress)
      Message.s= Message + " ["+TheIPAddress+"] with "
    EndIf   
  Else
    ; This is an IP Address in a string
    TheIPAddress = StrAdd
    lngDAddress = lngNewAddress(strAdd) ; Convert to a numeric
    Message.s = Message + " with "
  EndIf   
  If TheIPAddress = "The Network can't be initialized."
    Message = Message + Chr(10) + Chr(10) + TheIPAddress
  ElseIf TheIPAddress = "A non-IP address was returned."
    Message = Message + Chr(10) + Chr(10) + TheIPAddress
  ElseIf TheIPAddress = "Unable to resolve domain name"
    Message = Message + Chr(10) + Chr(10) + TheIPAddress
  Else  
  lngHPort = IcmpCreateFile_()
  Message = Message + Str(MsgLen)+" bytes of data:"+Chr(10)+Chr(10)
  For i = 1 To 4
    PacketCount+1
    lngResult = IcmpSendEcho_(lngHPort, lngDAddress, strMessage, Len(strMessage), 0, ECHO, SizeOf(ICMP_ECHO_REPLY), PING_TIMEOUT)
    If lngResult = 0
      Message=Message + "Reply from "+TheIPAddress+":  "
      Message= Message + "Error no: "+ Str(ECHO\Status) + Chr(10)
      PingResult(i) = -1
      LostPackets+1
    Else
      PingResult(i) = ECHO\RoundTripTime
      bytes(i) = ECHO\Datasize
      ttls(i) =  ECHO\Options
      RemoteIP.s = IPString(ECHO\Address)
      Message=Message + "Reply from "+RemoteIP+":  bytes = "+Str(bytes(i))+" time = "+Str(PingResult(i))+"ms TTL = "+StrU(ttls(i),#Byte)+Chr(10)
      RecdPackets+1
      SuccessTrip+1
    EndIf
    Delay(100)
  Next
  Message=Message + Chr(10) + "Ping statistics for "+CheckOut+":"+Chr(10)
  Message=Message + "   Packets: Sent = " + Str(PacketCount)
  Message=Message + ", Received = " + Str(RecdPackets)
  Message=Message + ", Lost = " + Str(LostPackets)
  If LostPackets = 0
    LostPercent = 0
  Else
    LostPercent = (LostPackets/PacketCount)*100
  EndIf
  Message=Message + " ("+StrF(LostPercent,0)+"% loss)"+Chr(10)+Chr(10)
  PingResult(5)=255
  PingResult(6)=0
  For i = 1 To 4
    If PingResult(i)> 0
      PingResult(6) = Maximum(PingResult(6),PingResult(i))
      PingResult(5) = Minimum(PingResult(5),PingResult(i))
      PingResult(0)+PingResult(i)
    EndIf
  Next
  MinTrip = PingResult(5)
  MaxTrip = PingResult(6)
  If RecdPackets
    AvgTrip = PingResult(0)/RecdPackets
  Else
    AvgTrip = PingResult(6)
  EndIf
  If AvgTrip > 0
    Message=Message + "Approximate round trip times in milli-seconds:"+Chr(10)
    Message=Message + "    Minimum = "+Str(MinTrip)+"ms,  Maximum = "+Str(MaxTrip)+",  Average = "+StrF(AvgTrip,2)+"ms"
  EndIf
  lngResult = IcmpCloseHandle_(lngHPort)
  ProcedureReturn PingResult
EndIf 
EndProcedure

Procedure GetIPbyName(NameIP.s) 
  TheIPAddress.s
  If InitNetwork() 
    pHostinfo = gethostbyname_(NameIP) 
    If pHostinfo = 0 
      TheIPAddress = "Unable to resolve domain name"
     Else 
      CopyMemory (pHostinfo, hostinfo.HOSTENT, SizeOf(HOSTENT)) 
      If hostinfo\h_addrtype <> #AF_INET 
        TheIPAddress = "A non-IP address was returned."
      Else 
        While PeekL(hostinfo\h_addr_list+AdressNumber*4) 
          ipAddress = PeekL(hostinfo\h_addr_list+AdressNumber*4) 
          TheIPAddress = StrU(PeekB(ipAddress),0)+"."+StrU(PeekB(ipAddress+1),0)+"."+StrU(PeekB(ipAddress+2),0)+"."+StrU(PeekB(ipAddress+3),0) 
          AdressNumber+1 
        Wend 
      EndIf 
    EndIf 
  Else 
    TheIPAddress = "The Network can't be initialized."
  EndIf 
  ProcedureReturn TheIPAddress 
EndProcedure 

Procedure.w Minimum(a.w,b1.w)
  If a < b1
    c1.w = a
  Else
    c1.w = b1
  EndIf
  ProcedureReturn c1
EndProcedure

Procedure.w Maximum(a.w,b1.w)
  If a > b1
    c1 = a
  Else
    c1 = b1
  EndIf
  ProcedureReturn c1
EndProcedure

Procedure GoDoIt(CheckStr.s)
  CheckOut = GetGadgetText(2)
  CheckOut = RemoveString(CheckOut, "http://") 
  CheckOut = RemoveString(CheckOut, "ftp://") 
  If Len(CheckOut)  
    Ping(CheckOut)
  Else
    CheckOut.s = GetGadgetText(4)
    Ping(CheckOut)
  EndIf    
  MessageRequester("PING2", Message, #MB_ICONINFORMATION)
  SetGadgetText(2,"")
  SetGadgetText(4,"")
  ActivateGadget(2)
EndProcedure 
I hope you and other forum members get some use for it.

Terry
oldefoxx
Enthusiast
Enthusiast
Posts: 532
Joined: Fri Jul 25, 2003 11:24 pm

Thanks for the complement.

Post by oldefoxx »

Actually, you can use Batch files with every version of Windows, including NT, 2000, and XP. You do not even need to use Start/Run/Cms tp get tp a DOS prompt first, although that is one way to do it. But as I showed, yoy can create it and do it from within a PureBasic program, or create the file and run it later by just clicking on it.

I tried you Ping2 program, and it works well. Thanks!
has-been wanna-be (You may not agree with what I say, but it will make you think).
Post Reply