// 得到本机IP private string GetLocalIP() { //本机IP地址 string strLocalIP = ""; //得到计算机名 string strPcName = Dns.GetHostName(); //得到本机IP地址数组 IPHostEntry ipEntry = Dns.GetHostEntry(strPcName); //遍历数组 foreach(var IPadd in ipEntry.AddressList) { //判断当前字符串是否为正确IP地址 if (IsRightIP(IPadd.ToString())) { //得到本地IP地址 strLocalIP = IPadd.ToString(); break; } } return strLocalIP; }
//得到网关地址 private string GetGateway() { string strGateway = ""; //获取所有网卡 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); //遍历数组 foreach (var netWork in nics) { //单个网卡的IP对象 IPInterfaceProperties ip = netWork.GetIPProperties(); //获取该IP对象的网关 GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses; foreach(var gateWay in gateways) { //如果能够Ping通网关 if(IsPingIP(gateWay.Address.ToString())) { //得到网关地址 strGateway = gateWay.Address.ToString(); //跳出循环 break; } } //如果已经得到网关地址 if (strGateway.Length > 0) { break; } } return strGateway; }
/// 尝试Ping指定IP是否能够Ping通 /// <param name="strIP">指定IP</param> /// <returns>true 是 false 否</returns> public static bool IsPingIP(string strIP) { try { Ping ping = new Ping(); //接受Ping返回值 PingReply reply = ping.Send(strIP, 1000); //Ping通 return true; } catch { //Ping失败 return false; } }