PSO2SERVER/Server/Network/Ipv4Addr.cs
Sancaros cd81d27f38 新增固定长度结构
修正部分数据包结构
2024-12-07 13:42:43 +08:00

77 lines
1.8 KiB
C#

using System;
public struct Ipv4Addr : IEquatable<Ipv4Addr>
{
private byte[] octets;
// 构造函数
public Ipv4Addr(byte[] octets)
{
if (octets == null || octets.Length != 4)
throw new ArgumentException("IPv4 address must have exactly 4 octets.");
this.octets = octets;
}
// 允许访问 octets 数组
public byte[] Octets => octets;
// 重写 Equals 方法
public override bool Equals(object obj)
{
return obj is Ipv4Addr other && Equals(other);
}
// 实现 IEquatable<T> 接口
public bool Equals(Ipv4Addr other)
{
for (int i = 0; i < 4; i++)
{
if (this.octets[i] != other.octets[i])
return false;
}
return true;
}
// 重写 GetHashCode 方法
public override int GetHashCode()
{
int hash = 17;
foreach (var octet in octets)
{
hash = hash * 31 + octet;
}
return hash;
}
// 提供一个用于显示的字符串格式
public override string ToString()
{
return string.Join(".", octets);
}
// 静态方法来解析字符串形式的 IPv4 地址
public static Ipv4Addr Parse(string ipString)
{
var parts = ipString.Split('.');
if (parts.Length != 4)
throw new ArgumentException("Invalid IPv4 address format.");
var octets = new byte[4];
for (int i = 0; i < 4; i++)
{
octets[i] = byte.Parse(parts[i]);
}
return new Ipv4Addr(octets);
}
// 重载 == 和 != 操作符
public static bool operator ==(Ipv4Addr left, Ipv4Addr right)
{
return left.Equals(right);
}
public static bool operator !=(Ipv4Addr left, Ipv4Addr right)
{
return !(left == right);
}
}