Address.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #region License
  2. /*
  3. ENet for C#
  4. Copyright (c) 2011 James F. Bellinger <jfb@zer7.com>
  5. Permission to use, copy, modify, and/or distribute this software for any
  6. purpose with or without fee is hereby granted, provided that the above
  7. copyright notice and this permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #endregion
  17. using System;
  18. using System.Net;
  19. using System.Text;
  20. namespace ENet
  21. {
  22. public unsafe struct Address : IEquatable<Address>
  23. {
  24. public const uint IPv4HostAny = Native.ENET_HOST_ANY;
  25. public const uint IPv4HostBroadcast = Native.ENET_HOST_BROADCAST;
  26. private Native.ENetAddress address;
  27. public override bool Equals(object obj)
  28. {
  29. return obj is Address && this.Equals((Address) obj);
  30. }
  31. public bool Equals(Address addr)
  32. {
  33. return this.Port == addr.Port && this.IP == addr.IP;
  34. }
  35. public override int GetHashCode()
  36. {
  37. return this.Port.GetHashCode() ^ this.IP.GetHashCode();
  38. }
  39. public string IP
  40. {
  41. get
  42. {
  43. var ip = new byte[256];
  44. fixed (byte* hostIP = ip)
  45. {
  46. if (Native.enet_address_get_host_ip(ref this.address, hostIP, (uint)ip.Length) < 0)
  47. {
  48. return null;
  49. }
  50. }
  51. return Encoding.ASCII.GetString(ip, 0, Native.strlen(ip));
  52. }
  53. }
  54. public string Host
  55. {
  56. get
  57. {
  58. var name = new byte[256];
  59. fixed (byte* hostName = name)
  60. {
  61. if (Native.enet_address_get_host(ref this.address, hostName, (uint)name.Length) < 0)
  62. {
  63. return null;
  64. }
  65. }
  66. return Encoding.ASCII.GetString(name, 0, Native.strlen(name));
  67. }
  68. set
  69. {
  70. Native.enet_address_set_host(ref this.address, Encoding.ASCII.GetBytes(value));
  71. }
  72. }
  73. public Native.ENetAddress NativeData
  74. {
  75. get
  76. {
  77. return this.address;
  78. }
  79. }
  80. public ushort Port
  81. {
  82. get
  83. {
  84. return this.address.port;
  85. }
  86. set
  87. {
  88. this.address.port = value;
  89. }
  90. }
  91. }
  92. }