I have written a program about ICMP protcol,which implements the PING command.Though everything runs well,i still have some questions.
There are two variables.One is "ep" which is an object of EndPoint class and the other is "iep" which is an Object of IPEndPoint class.There are something strange happened.After casting the "iep" to "ep",the value of "ep" is changed.For example,if "iep" is "180.97.33.107" and after casting "iep" to "ep",the value of "ep" will be "192.168.1.1".
The question about function GetHostEntry() is that if the input is domain name, the program works successfully,while if the input is IP address,the program will throw an exception that host can not be found.
Here is the code.
private void but_simping_Click(object sender, EventArgs e)
{
try
{
if (txt_dstip.Text == "")
{
MessageBox.Show("IP地址不能为空!");
return;
}
byte[] msgData = new byte[1024];
int receive;
Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
IPHostEntry iphentry = Dns.GetHostEntry(txt_dstip.Text.Trim());
IPEndPoint iep = new IPEndPoint(iphentry.AddressList[0], 0);
EndPoint ep = (EndPoint)iep;
ICMP icmp = new ICMP();
icmp.packType = 0x08;
icmp.packCode = 0x00;
icmp.CheckSum = 0;
Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, icmp.Msg, 0, 2);
Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, icmp.Msg, 2, 2);
msgData = Encoding.ASCII.GetBytes("This is a test packet");
Buffer.BlockCopy(msgData, 0, icmp.Msg, 4, msgData.Length);
icmp.msgSize = msgData.Length + 4;
int pktsize = icmp.msgSize + 4;
UInt16 checksum = icmp.getCheckSum();
icmp.CheckSum = checksum;
host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
host.SendTo(icmp.getBytes(), pktsize, SocketFlags.None, iep);
msgData = new byte[1024];
receive = host.ReceiveFrom(msgData, ref ep);
ShowICMPMsg(msgData, receive, iep);
host.Close();
}
catch (SocketException ee)
{
MessageBox.Show(ee.Message.ToString());
return;
}
finally
{
}
}
PS:i'm not a native english speaker.If there're some mistakes,just point it out,thanks.