Windows Mobile Ping 命令实现
Windows Mobile是没有现成的Ping可用的,所以需要自己做一个。一种最直接的想法就是用Socket实现ICMP协议(针对PING命令的部分),对于桌 面版的.Net Framework中的Socket,只要如下进行定义,就可以是实现收发ICMP数据包。
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
但是很不幸的是.Net compact Framework不支持ProtocolType.Icmp参数,所以也无从用Socket实现了。幸好天无绝人之路,Windows Mobile还提供了Icmp的API接口,可以通过这些API接口,实现PING命令的功能,核心代码如下:
{
#region P/Invoke
[DllImport("\\windows\\iphlpapi.dll", SetLastError = true)]
static extern IntPtr IcmpCreateFile();
[DllImport("\\windows\\iphlpapi.dll", SetLastError = true)]
static extern bool IcmpCloseHandle(IntPtr handle);
[DllImport("\\windows\\iphlpapi.dll", SetLastError = true)]
static extern Int32 IcmpSendEcho(IntPtr icmpHandle, Int32 destinationAddress, String requestData, Int16 requestSize, ref IP_OPTION_INFORMATION requestOptions, ref ICMP_ECHO_REPLY replyBuffer, Int32 replySize, Int32 timeout);
[StructLayout(LayoutKind.Sequential)]
public struct IP_OPTION_INFORMATION
{
public byte TTL;
public byte TOS;
public byte Flags;
public byte OptionsSize;
public IntPtr OptionsData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct ICMP_ECHO_REPLY
{
public int Address;
public int Status;
public int RoundTripTime;
public Int16 DataSize;
public Int16 Reserved;
public IntPtr DataPtr;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 250)]
public String Data;
public IP_OPTION_INFORMATION Options;
}
#endregion
public static int ping(string ip, int timeout,out string info)
{
IPEndPoint host = new IPEndPoint(Dns.GetHostEntry(ip).AddressList[0], 0);
if (host == null | Environment.OSVersion.Platform != PlatformID.WinCE)
{
info = "ip error!";
return -1;
}
int result = -1;
IntPtr ICMPHandle;
Int32 iIP;
String sData;
IP_OPTION_INFORMATION oICMPOptions = new IP_OPTION_INFORMATION();
ICMP_ECHO_REPLY ICMPReply = new ICMP_ECHO_REPLY();
Int32 iReplies;
ICMPHandle = IcmpCreateFile();
iIP = BitConverter.ToInt32(host.Address.GetAddressBytes(), 0);
sData = "abcdefghijklmnopqrstuvwxyz012345";
oICMPOptions.TTL = 255;
iReplies = IcmpSendEcho(ICMPHandle, iIP, sData, (Int16)sData.Length, ref oICMPOptions, ref ICMPReply, Marshal.SizeOf(ICMPReply), timeout);
if (ICMPReply.Status == 0)
{
result = ICMPReply.RoundTripTime;
info = "ping bytes=" + sData.Length.ToString() + " time=" + result.ToString() + "ms TTL=" + oICMPOptions.TTL.ToString();
}
else
{
info = "ping " + ip + " timed out.";
}
IcmpCloseHandle(ICMPHandle);
return result;
}
}
最终程序运行后的界面如下:
需要注意的是,GPRS连接必须是CMNET(关于如何建立GPRS连接,有兴趣的朋友可以参考我以前写的文章:让智能手机和居家电脑互联互通(WM6 GPRS)),否则是无法PING通公网IP的,此外我们发现Windows Mobile手机的IP为10.x.x.x,我们知道10开头的IP地址是A类地址,查相关资料,我们可知10.0.0.0到 10.255.255.255是私有地址(所谓的私有地址就是在互联网上不使用,而被用在局域网络中的地址)。每个A类地址理论上可连接16777214 台主机,这大约是1千六百万台,这也是同时使用GPRS的手机数上限了。由于Windows Mobile手机分配的IP地址不是公网IP,所以很遗憾,我们不能在PC上Ping Windows Mobile手机,也就无法测试PC的Ping出命令是否正常了。