11. 用下列代碼替換Form1.cs文件中的button1組件的Click事件對應的處理代碼,下列代碼的作用是創建、發送ICMP報文,實現Ping命令:
Private Void Button1_click ( Object Sender , System.eventargs E )
{
Listbox1.items.clear ( ) ;
String HostclIEnt = Textbox1.text ;
Int K ;
For ( K = 0 ; K < 3 ; K++ )
{
Socket Socket = New Socket ( Addressfamily.internetwork , Sockettype.raw , Protocoltype.icmp ) ;
Iphostentry Hostinfo ;
Try
{
//解析主機ip入口
Hostinfo = Dns.gethostbyname ( HostclIEnt ) ;
}
Catch ( Exception )
{
//解析主機名錯誤。
Listbox1.items.add ( "沒有發現此主機!" ) ;
Return ;
}
// 取服務器端主機的30號端口
Endpoint Hostpoint = ( Endpoint ) New Ipendpoint ( Hostinfo.addresslist[ 0 ] , 30 ) ;
Iphostentry ClIEntinfo ;
Clientinfo = Dns.gethostbyname ( HostclIEnt ) ;
// 取客戶機端主機的30端口
Endpoint Clientpoint = ( Endpoint ) New Ipendpoint ( ClIEntinfo.addresslist[ 0 ] , 30 ) ;
//設置icmp報文
Int Datasize = 4 ; // Icmp數據包大小 ;
Int Packetsize = Datasize + 8 ;//總報文長度
Const Int Icmp_echo = 8 ;
Icmppacket Packet = New Icmppacket ( Icmp_echo , 0 , 0 , 45 , 0 , Datasize ) ;
Byte [ ] Buffer = New Byte [ Packetsize ] ;
Int Index = Packet.countbyte ( Buffer ) ;
//報文出錯
If ( Index != Packetsize )
{
Listbox1.items.add ( "報文出現問題!" ) ;
Return ;
}
Int Cksum_buffer_length = ( Int ) Math.ceiling ( ( ( Double )index )/ 2 ) ;
Uint16 [ ] Cksum_buffer = New Uint16 [ Cksum_buffer_length ] ;
Int Icmp_header_buffer_index = 0 ;
For ( Int I = 0 ; I < Cksum_buffer_length ; I++ )
{
//將兩個byte轉化為一個uint16
Cksum_buffer[ I ] = Bitconverter.touint16 ( Buffer , Icmp_header_buffer_index ) ;
Icmp_header_buffer_index += 2 ;
}
//將校驗和保存至報文裡
Packet.checksum = Icmppacket.sumofcheck ( Cksum_buffer ) ;
// 保存校驗和後,再次將報文轉化為數據包
Byte [ ] Senddata = New Byte [ Packetsize ] ;
Index = Packet.countbyte ( Senddata ) ;
//報文出錯
If ( Index != Packetsize )
{
Listbox1.items.add ( "報文出現問題!" ) ;
Return ;
}
Int Nbytes = 0 ;
//系統計時開始
Int Starttime = Environment.tickcount ;
//發送數據包
If ( ( Nbytes = Socket.sendto ( Senddata , Packetsize , Socketflags.none , Hostpoint ) ) == -1 )
{
Listbox1.items.add ( "無法傳送報文!" ) ;
}
Byte [ ] Receivedata = New Byte[ 256 ] ; //接收數據
Nbytes = 0 ;
Int Timeout = 0 ;
Int Timeconsume = 0 ;
While ( True )
{
Nbytes = Socket.receivefrom ( Receivedata , 256 , Socketflags.none , Ref ClIEntpoint ) ;
If ( Nbytes == -1 )
{
Listbox1.items.add ( "主機沒有響應!" ) ;
Break ;
}
Else If ( Nbytes > 0 )
{
Timeconsume = System.environment.tickcount - Starttime ;
//得到發送報文到接收報文之間花費的時間
Listbox1.items.add ( "reply From " + Hostinfo.addresslist[ 0 ].tostring ( ) + " In "
+ Timeconsume + "ms :bytes Received " + Nbytes ) ;
Break ;
}
Timeconsume = Environment.tickcount - Starttime ;
If ( Timeout > 1000 )
{
Listbox1.items.add ( "time Out" ) ;
Break ;
}
}
//關閉套接字
Socket.close ( ) ;
}
}