IpHelper.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #if ENABLE_MONO && (DEVELOPMENT_BUILD || UNITY_EDITOR)
  2. #if UNITY_ANDROID && !UNITY_EDITOR
  3. #define MOBILE_ANDROID
  4. #endif
  5. #if UNITY_IOS && !UNITY_EDITOR
  6. #define MOBILE_IOS
  7. #endif
  8. #if MOBILE_ANDROID || MOBILE_IOS
  9. #define MOBILE
  10. #endif
  11. using System;
  12. using System.Net.NetworkInformation;
  13. using System.Net.Sockets;
  14. namespace SingularityGroup.HotReload {
  15. static class IpHelper {
  16. // get my local ip address
  17. static DateTime cachedAt;
  18. static string ipCached;
  19. public static string GetIpAddressCached() {
  20. if (string.IsNullOrEmpty(ipCached) || DateTime.UtcNow - cachedAt > TimeSpan.FromSeconds(5)) {
  21. ipCached = GetIpAddress();
  22. cachedAt = DateTime.UtcNow;
  23. }
  24. return ipCached;
  25. }
  26. public static string GetIpAddress() {
  27. var ip = GetLocalIPv4(NetworkInterfaceType.Wireless80211);
  28. if (string.IsNullOrEmpty(ip)) {
  29. return GetLocalIPv4(NetworkInterfaceType.Ethernet);
  30. }
  31. return ip;
  32. }
  33. private static string GetLocalIPv4(NetworkInterfaceType _type) {
  34. string output = "";
  35. foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) {
  36. if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up) {
  37. foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses) {
  38. if (ip.Address.AddressFamily == AddressFamily.InterNetwork && IsLocalIp(ip.Address.MapToIPv4().GetAddressBytes())) {
  39. output = ip.Address.ToString();
  40. }
  41. }
  42. }
  43. }
  44. return output;
  45. }
  46. // https://datatracker.ietf.org/doc/html/rfc1918#section-3
  47. static bool IsLocalIp(byte[] ipAddress) {
  48. return ipAddress[0] == 10
  49. || ipAddress[0] == 172
  50. && ipAddress[1] >= 16
  51. && ipAddress[1] <= 31
  52. || ipAddress[0] == 192
  53. && ipAddress[1] == 168;
  54. }
  55. }
  56. }
  57. #endif