unity判断是否联网(转载)

using UnityEngine;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using Ping = System.Net.NetworkInformation.Ping;


/// <summary>
/// 简化
/// 封装函数 —— 检测本地网络链接状态
/// </summary>
public class ChinarWeb : MonoBehaviour
{
    [DllImport("winInet.dll")]                                                            //引用外部库
    private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved); //库中函数


    void Start()
    {
        ChinarPing("www.chinar.xin");
    }


    void Update()
    {
        IsConnectedInternet();
    }


    /// <summary>
    /// 判断本地的连接状态
    /// </summary>
    private static bool IsConnectedInternet()
    {
        int dwFlag = new int();
        if (!InternetGetConnectedState(ref dwFlag, 0))
        {
            PrintR("当前没有联网,请您先联网后再进行操作!");
            if ((dwFlag & 0x14) == 0) return false;
            Debug.LogWarning("本地系统处于脱机模式。");
            return false;
        }
        else
        {
            if ((dwFlag & 0x01) != 0)
            {
                Print("调制解调器上网。");
                return true;
            }
            else if ((dwFlag & 0x02) != 0)
            {
                Print("网卡上网。");
                return true;
            }
            else if ((dwFlag & 0x04) != 0)
            {
                Print("代理服务器上网。");
                return true;
            }
            else if ((dwFlag & 0x40) != 0)
            {
                Print("虽然可以联网,但可能链接也可能不连接。");
                return true;
            }
        }

        return false;
    }


    /// <summary>
    /// Chinar 闪亮输出
    /// </summary>
    public static void Print(string str)
    {
        Debug.Log($"<b><color=lime><size={12}>{str}</size></color></b>");
    }


    /// <summary>
    /// Chinar 警告输出
    /// </summary>
    public static void PrintR(string str)
    {
        Debug.Log($"<b><color=red><size={12}>{str}</size></color></b>");
    }


    /// <summary>
    /// Ping命令检测网络是否畅通
    /// </summary>
    /// <param name="url">URL地址</param>
    /// <returns>是否ping通</returns>
    public static bool ChinarPing(string url)
    {
        bool isSucceed = true;
        Ping ping      = new Ping();
        try
        {
            var pingReply = ping.Send(url);
            if (pingReply != null && pingReply.Status != IPStatus.Success)
            {
                isSucceed = false;
            }

            if (pingReply != null) print("Ping 网址:<" + url + ">------状态:" + pingReply.Status);
        }
        catch
        {
            isSucceed = false;
        }

        return isSucceed;
    }
}

来源https://blog.csdn.net/ChinarCSDN/article/details/85085289

https://www.cnblogs.com/atree/archive/2011/04/01/CSharp-Internet-wininet-dll.html

猜你喜欢

转载自blog.csdn.net/weixin_41995872/article/details/89485811