툴/유니티

네트워크 다운로드,업로드 속도 가져오기

스튜디오 오버그래픽스 2023. 5. 16. 21:05
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.NetworkInformation;
using TMPro;

public class NetworkSpeedCheck : MonoBehaviour
{
    [SerializeField] private TMP_Text DownloadText, UPloadText;

    long previousbytessend = 0;
    long previousbytesreceived = 0;
    long downloadspeed;
    long uploadspeed;
    IPv4InterfaceStatistics interfaceStats;

    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("NetworkCheck", 1f, 1f);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void NetworkCheck()
    {
        //Must Initialize it each second to update values;
        interfaceStats = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics();

        //SPEED = MAGNITUDE / TIME ; HERE, TIME = 1 second Hence :
        uploadspeed = (interfaceStats.BytesSent - previousbytessend) / 1024; //In KB/s
        downloadspeed = (interfaceStats.BytesReceived - previousbytesreceived) / 1024;

        previousbytessend = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics().BytesSent;
        previousbytesreceived = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics().BytesReceived;

        //downloadspeedlabel.Text = Math.Round(downloadspeed, 2) + " KB/s"; //Rounding to 2 decimal places
        //uploadspeedlabel.Text = Math.Round(uploadspeed, 2) + "KB/s";

        DownloadText.text = downloadspeed.ToString();
        UPloadText.text = uploadspeed.ToString();
    }
}