In his spare time, Lee wrote a method to traverse IP segments without operating the IP string and return the list of active IP addresses. In other words, he simply pasted the code.
Iphost class
Using System;
Using System. Collections. Generic;
Using System. text;
Using System. net;
Using System. diagnostics;
NamespaceTest2. _ 0
{
ClassIphost
{
PublicIphost ()
{
}
/// <Summary>
/// Obtains the list of active IP addresses in an IP segment.
/// </Summary>
/// <Param name = "startip"> Start IP </Param>
/// <Param name = "endip"> End IP </Param>
/// <Returns> </returns>
Public List < IPaddress > Getliveip (IPaddress startip, IPaddress endip)
{
List < IPaddress > Iplist = New List < IPaddress > ();
IPaddress currentip = New IPaddress (startip. Address );
Currentip = Startip;
While (Currentip. Address <= Endip. Address)
{
If (Getipstate (currentip) = " Connection " )
{
Iplist. Add (currentip );
}
Currentip = Nextip (currentip );
}
Return Iplist;
}
/// <Summary>
/// Obtain its next IPaddress from an IPaddress
/// </Summary>
/// <Param name = "theip"> IPaddress </Param>
/// <Returns> </returns>
Public IPaddress nextip (IPaddress theip)
{
Uint Startuint = ( Uint ) IPaddress. networktohostorder (( Int ) Theip. Address );
LongNetworklong=(Long) IPaddress. hosttonetworkorder ((Int) (Startuint+ 1));
Return NewIPaddress (networklong );
}
/// <Summary>
/// Determines whether the IP address is active
/// </Summary>
/// <Param name = "theip"> </param>
/// <Returns> </returns>
Public Bool Ipislive (IPaddress theip)
{
System. net. networkinformation. Ping pi = New System. net. networkinformation. Ping ();
System. net. networkinformation. pingreply PR = Pi. Send (theip );
If (PR. Status & System. net. networkinformation. ipstatus. Success) = System. net. networkinformation. ipstatus. Success)
{
Return True ;
}
Else
{
Return False ;
}
}
/// <Summary>
/// Use cmd to determine the IP status (the old method is to keep a souvenir)
/// </Summary>
/// <Param name = "theip"> </param>
/// <Returns> </returns>
Public String Getipstate (IPaddress theip)
{
Process PCs = New Process ();
PCS. startinfo. filename = " Cmd.exe " ;
PCS. startinfo. useshellexecute = False ;
PCS. startinfo. redirectstandardinput = True ;
PCS. startinfo. redirectstandardoutput = True ;
PCS. startinfo. redirectstandarderror = True ;
PCS. startinfo. createnowindow = True ;
String Pingstr;
PCS. Start ();
PCS. standardinput. writeline ( " Ping-N 1 " + Theip. tostring ());
PCS. standardinput. writeline ( " Exit " );
String Strrst = PCS. standardoutput. readtoend ();
If (Strrst. indexof ( " (0% loss) " ) ! = - 1 )
Pingstr = " Connection " ;
Else If (Strrst. indexof ( " Destination host unreachable. " ) ! = - 1 )
Pingstr = " Unable to reach target host " ;
Else If (Strrst. indexof ( " Request timed out. " ) ! = - 1 )
Pingstr = " Timeout " ;
Else If (Strrst. indexof ( " Unknown host " ) ! = - 1 )
Pingstr = " Unable to Resolve Host " ;
Else
Pingstr = Strrst;
PCS. Close ();
Return Pingstr;
}
}
}