问题描述
怎么写c#代码实现是否ping通的服务器谢啦兄弟
解决方案
解决方案二:
publicboolcheckConn(){try{System.Net.IPHostEntryip;System.Net.IPAddressaddress;address=System.Net.IPAddress.Parse("202.103.24.68");ip=System.Net.Dns.GetHostByAddress(address);returntrue;}catch(Exception){returnfalse;}}IP你自己写通了就是true
解决方案三:
//声明常量constintSOCKET_ERROR=-1;constintICMP_ECHO=8;publicstaticInt32Serialize(IcmpPacketpacket,Byte[]Buffer,Int32PacketSize,Int32PingData){//取得报文内容,转化为字节数组,然后计算报文的长度Int32cbReturn=0;//数据报结构转化为数组intIndex=0;Byte[]b_type=newByte[1];b_type[0]=(packet.Type);Byte[]b_code=newByte[1];b_code[0]=(packet.SubCode);Byte[]b_cksum=BitConverter.GetBytes(packet.CheckSum);Byte[]b_id=BitConverter.GetBytes(packet.Identifier);Byte[]b_seq=BitConverter.GetBytes(packet.SequenceNumber);Array.Copy(b_type,0,Buffer,Index,b_type.Length);Index+=b_type.Length;Array.Copy(b_code,0,Buffer,Index,b_code.Length);Index+=b_code.Length;Array.Copy(b_cksum,0,Buffer,Index,b_cksum.Length);Index+=b_cksum.Length;Array.Copy(b_id,0,Buffer,Index,b_id.Length);Index+=b_id.Length;Array.Copy(b_seq,0,Buffer,Index,b_seq.Length);Index+=b_seq.Length;//复制数据Array.Copy(packet.Data,0,Buffer,Index,PingData);Index+=PingData;if(Index!=PacketSize/*sizeof(IcmpPacket)*/){cbReturn=-1;returncbReturn;}cbReturn=Index;returncbReturn;}///<summary>///校验和算法///</summary>publicstaticUInt16checksum(UInt16[]buffer,intsize){Int32cksum=0;intcounter;counter=0;/*把ICMP报头二进制数据以2字节为单位累加起来*/while(size>0){UInt16val=buffer[counter];cksum+=Convert.ToInt32(buffer[counter]);counter+=1;size-=1;}/*若ICMP报头为奇数个字节,会剩下最后一字节。把最后一个字节视为一个*2字节数据的高字节,这个2字节数据的低字节为0,继续累加*/cksum=(cksum>>16)+(cksum&0xffff);cksum+=(cksum>>16);return(UInt16)(~cksum);}privatevoidbutton1_Click(objectsender,System.EventArgse){//执行PINGthis.richTextBox1.Text="";for(intp=0;p<10;p++){try{stringHostName=this.textBox1.Text;intnBytes=0;intdwStart=0,dwStop=0;//初始化一个ICMP类型的SocketSocketsocket=newSocket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.Icmp);//取得目标主机的主机名IPHostEntryserverHE=Dns.GetHostByName(HostName);IPEndPointipepServer=newIPEndPoint(serverHE.AddressList[0],0);EndPointepServer=(ipepServer);IPHostEntryfromHE=Dns.GetHostByName(Dns.GetHostName());IPEndPointipEndPointFrom=newIPEndPoint(fromHE.AddressList[0],0);EndPointEndPointFrom=(ipEndPointFrom);intPacketSize=0;IcmpPacketpacket=newIcmpPacket();//构造数据报packet.Type=ICMP_ECHO;packet.SubCode=0;packet.CheckSum=UInt16.Parse("0");packet.Identifier=UInt16.Parse("45");packet.SequenceNumber=UInt16.Parse("0");intPingData=32;//sizeof(IcmpPacket)-8;packet.Data=newByte[PingData];//初始化Packet.Datafor(inti=0;i<PingData;i++){packet.Data[i]=(byte)'#';}//保存数据报的长度PacketSize=PingData+8;Byte[]icmp_pkt_buffer=newByte[PacketSize];Int32Index=0;//调用Serialize方法//报文总共的字节数Index=Serialize(packet,icmp_pkt_buffer,PacketSize,PingData);if(Index==-1){this.richTextBox1.Text+="报文大小有错!n";return;}//转化为Uint16类型的数组,取得数据报长度的一半Doubledouble_length=Convert.ToDouble(Index);Doubledtemp=Math.Ceiling(double_length/2);intcksum_buffer_length=Convert.ToInt32(dtemp);//生成一个字节数组UInt16[]cksum_buffer=newUInt16[cksum_buffer_length];//初始化Uint16类型arrayinticmp_header_buffer_index=0;for(inti=0;i<cksum_buffer_length;i++){cksum_buffer[i]=BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index);icmp_header_buffer_index+=2;}//调用checksum,返回检查和UInt16u_cksum=checksum(cksum_buffer,cksum_buffer_length);//检查和存在报文中packet.CheckSum=u_cksum;Byte[]sendbuf=newByte[PacketSize];//再次检查报文大小Index=Serialize(packet,sendbuf,PacketSize,PingData);//如果有错,则报告错误if(Index==-1){this.richTextBox1.Text+="报文大小有错!n";return;}dwStart=System.Environment.TickCount;//开始时间//用socket发送数据报if((nBytes=socket.SendTo(sendbuf,PacketSize,0,epServer))==SOCKET_ERROR){this.richTextBox1.Text+="不能发送数据包!n";}//初始化缓冲区.接受缓冲区//ICMP头+IP头(20字节)Byte[]ReceiveBuffer=newByte[256];nBytes=0;//接受字节流boolrecd=false;inttimeout=0;//循环检查目标主机响应时间while(!recd){nBytes=socket.ReceiveFrom(ReceiveBuffer,256,0,refEndPointFrom);if(nBytes==SOCKET_ERROR){this.richTextBox1.Text+="目标主机没有响应!n";recd=true;break;}elseif(nBytes>0){dwStop=System.Environment.TickCount-dwStart;this.richTextBox1.Text+="数据来自主机:"+this.textBox1.Text+",收到的字节数:"+nBytes+",耗时:"+dwStop+"msn";recd=true;break;}timeout=System.Environment.TickCount-dwStart;if(timeout>1000){this.richTextBox1.Text+="连接超时!n";recd=true;}}//关闭socketsocket.Close();}catch(ExceptionErr){MessageBox.Show("PING目标主机操作失败!错误信息是:"+Err.Message,"信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);return;}}}}publicclassIcmpPacket{publicByteType;//消息类型publicByteSubCode;//子码类型publicUInt16CheckSum;//校检和publicUInt16Identifier;//标志符publicUInt16SequenceNumber;//顺序号publicByte[]Data;//数据}//ICMP包}
仅供参考!
解决方案四:
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Threading;usingSystem.Net.NetworkInformation;namespaceRemoteStationProgram{classPingServer{publicstaticboolping(stringServerIP){PingpingSender=newPing();PingOptionsoptions=newPingOptions();options.DontFragment=true;stringdata="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";byte[]buffer=Encoding.ASCII.GetBytes(data);inttimeout=120;PingReplyreply=pingSender.Send(ServerIP,timeout,buffer,options);return(reply.Status==IPStatus.Success);}}}
解决方案五:
//声明常量constintSOCKET_ERROR=-1;constintICMP_ECHO=8;publicstaticInt32Serialize(IcmpPacketpacket,Byte[]Buffer,Int32PacketSize,Int32PingData){//取得报文内容,转化为字节数组,然后计算报文的长度Int32cbReturn=0;//数据报结构转化为数组intIndex=0;Byte[]b_type=newByte[1];b_type[0]=(packet.Type);Byte[]b_code=newByte[1];b_code[0]=(packet.SubCode);Byte[]b_cksum=BitConverter.GetBytes(packet.CheckSum);Byte[]b_id=BitConverter.GetBytes(packet.Identifier);Byte[]b_seq=BitConverter.GetBytes(packet.SequenceNumber);Array.Copy(b_type,0,Buffer,Index,b_type.Length);Index+=b_type.Length;Array.Copy(b_code,0,Buffer,Index,b_code.Length);Index+=b_code.Length;Array.Copy(b_cksum,0,Buffer,Index,b_cksum.Length);Index+=b_cksum.Length;Array.Copy(b_id,0,Buffer,Index,b_id.Length);Index+=b_id.Length;Array.Copy(b_seq,0,Buffer,Index,b_seq.Length);Index+=b_seq.Length;//复制数据Array.Copy(packet.Data,0,Buffer,Index,PingData);Index+=PingData;if(Index!=PacketSize/*sizeof(IcmpPacket)*/){cbReturn=-1;returncbReturn;}cbReturn=Index;returncbReturn;}///<summary>///校验和算法///</summary>publicstaticUInt16checksum(UInt16[]buffer,intsize){Int32cksum=0;intcounter;counter=0;/*把ICMP报头二进制数据以2字节为单位累加起来*/while(size>0){UInt16val=buffer[counter];cksum+=Convert.ToInt32(buffer[counter]);counter+=1;size-=1;}/*若ICMP报头为奇数个字节,会剩下最后一字节。把最后一个字节视为一个*2字节数据的高字节,这个2字节数据的低字节为0,继续累加*/cksum=(cksum>>16)+(cksum&0xffff);cksum+=(cksum>>16);return(UInt16)(~cksum);}privatevoidbutton1_Click(objectsender,System.EventArgse){//执行PINGthis.richTextBox1.Text="";for(intp=0;p<10;p++){try{stringHostName=this.textBox1.Text;intnBytes=0;intdwStart=0,dwStop=0;//初始化一个ICMP类型的SocketSocketsocket=newSocket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.Icmp);//取得目标主机的主机名IPHostEntryserverHE=Dns.GetHostByName(HostName);IPEndPointipepServer=newIPEndPoint(serverHE.AddressList[0],0);EndPointepServer=(ipepServer);IPHostEntryfromHE=Dns.GetHostByName(Dns.GetHostName());IPEndPointipEndPointFrom=newIPEndPoint(fromHE.AddressList[0],0);EndPointEndPointFrom=(ipEndPointFrom);intPacketSize=0;IcmpPacketpacket=newIcmpPacket();//构造数据报packet.Type=ICMP_ECHO;packet.SubCode=0;packet.CheckSum=UInt16.Parse("0");packet.Identifier=UInt16.Parse("45");packet.SequenceNumber=UInt16.Parse("0");intPingData=32;//sizeof(IcmpPacket)-8;packet.Data=newByte[PingData];//初始化Packet.Datafor(inti=0;i<PingData;i++){packet.Data[i]=(byte)'#';}//保存数据报的长度PacketSize=PingData+8;Byte[]icmp_pkt_buffer=newByte[PacketSize];Int32Index=0;//调用Serialize方法//报文总共的字节数Index=Serialize(packet,icmp_pkt_buffer,PacketSize,PingData);if(Index==-1){this.richTextBox1.Text+="报文大小有错!n";return;}//转化为Uint16类型的数组,取得数据报长度的一半Doubledouble_length=Convert.ToDouble(Index);Doubledtemp=Math.Ceiling(double_length/2);intcksum_buffer_length=Convert.ToInt32(dtemp);//生成一个字节数组UInt16[]cksum_buffer=newUInt16[cksum_buffer_length];//初始化Uint16类型arrayinticmp_header_buffer_index=0;for(inti=0;i<cksum_buffer_length;i++){cksum_buffer[i]=BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index);icmp_header_buffer_index+=2;}//调用checksum,返回检查和UInt16u_cksum=checksum(cksum_buffer,cksum_buffer_length);//检查和存在报文中packet.CheckSum=u_cksum;Byte[]sendbuf=newByte[PacketSize];//再次检查报文大小Index=Serialize(packet,sendbuf,PacketSize,PingData);//如果有错,则报告错误if(Index==-1){this.richTextBox1.Text+="报文大小有错!n";return;}dwStart=System.Environment.TickCount;//开始时间//用socket发送数据报if((nBytes=socket.SendTo(sendbuf,PacketSize,0,epServer))==SOCKET_ERROR){this.richTextBox1.Text+="不能发送数据包!n";}//初始化缓冲区.接受缓冲区//ICMP头+IP头(20字节)Byte[]ReceiveBuffer=newByte[256];nBytes=0;//接受字节流boolrecd=false;inttimeout=0;//循环检查目标主机响应时间while(!recd){nBytes=socket.ReceiveFrom(ReceiveBuffer,256,0,refEndPointFrom);if(nBytes==SOCKET_ERROR){this.richTextBox1.Text+="目标主机没有响应!n";recd=true;break;}elseif(nBytes>0){dwStop=System.Environment.TickCount-dwStart;this.richTextBox1.Text+="数据来自主机:"+this.textBox1.Text+",收到的字节数:"+nBytes+",耗时:"+dwStop+"msn";recd=true;break;}timeout=System.Environment.TickCount-dwStart;if(timeout>1000){this.richTextBox1.Text+="连接超时!n";recd=true;}}//关闭socketsocket.Close();}catch(ExceptionErr){MessageBox.Show("PING目标主机操作失败!错误信息是:"+Err.Message,"信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);return;}}}}publicclassIcmpPacket{publicByteType;//消息类型publicByteSubCode;//子码类型publicUInt16CheckSum;//校检和publicUInt16Identifier;//标志符publicUInt16SequenceNumber;//顺序号publicByte[]Data;//数据}//ICMP包}
仅供参考!