ln.types/net/IPv4.cs

119 lines
3.0 KiB
C#

using System;
using System.Linq;
using System.Net;
using ln.types.odb;
using System.Collections.Generic;
using ln.types.odb.values;
namespace ln.types.net
{
public class IPv4
{
public static readonly IPv4 ANY = new IPv4(0);
public static IPv4 Parse(string sip)
{
string[] sbytes = sip.Split('.');
return new IPv4(sbytes.Select(s=>(byte)int.Parse(s)).ToArray());
}
private readonly uint _ip;
private IPv4()
{ }
public IPv4(uint ip)
{
_ip = ip;
}
public IPv4(byte[] bytes)
{
if (bytes.Length >= 4)
_ip = BitConverter.ToUInt32(bytes.Reverse().ToArray(), 0);
else
_ip = 0;
}
public IPv4(byte[] bytes,int offset)
{
_ip = BitConverter.ToUInt32(bytes.Slice(offset,4).BigEndian(),0);
}
public byte[] IPBytes
{
get => BitConverter.GetBytes(_ip).Reverse().ToArray();
}
public uint AsUInt => _ip;
public override int GetHashCode()
{
return (int)_ip;
}
public override bool Equals(object obj)
{
if (obj is IPAddress)
obj = new IPv4((obj as IPAddress).GetAddressBytes());
if (obj is IPv4)
{
return ((obj as IPv4)._ip == _ip);
}
return false;
}
public override string ToString()
{
return String.Format("{0}", String.Join(".", IPBytes.Select((x) => x.ToString())));
}
public static IPv4 operator ++(IPv4 ip)
{
return new IPv4(ip._ip + 1);
}
public static IPv4 operator --(IPv4 ip)
{
return new IPv4(ip._ip - 1);
}
public static bool operator <=(IPv4 a, IPv4 b)
{
return a._ip <= b._ip;
}
public static bool operator >=(IPv4 a, IPv4 b)
{
return a._ip >= b._ip;
}
public static bool operator <(IPv4 a, IPv4 b)
{
return a._ip < b._ip;
}
public static bool operator >(IPv4 a, IPv4 b)
{
return a._ip > b._ip;
}
public static int operator +(IPv4 a, IPv4 b)
{
return (int)a._ip + (int)b._ip;
}
public static int operator -(IPv4 a, IPv4 b)
{
return (int)a._ip - (int)b._ip;
}
public static IPv4 operator +(IPv4 a, int b)
{
return new IPv4((uint)(a._ip + b));
}
public static IPv4 operator -(IPv4 a, int b)
{
return new IPv4((uint)(a._ip + b));
}
public static implicit operator IPAddress(IPv4 ip) => new IPAddress(ip.IPBytes);
public static implicit operator IPv4(IPAddress ip) => new IPv4(ip.GetAddressBytes());
public static implicit operator IPv6(IPv4 ip) => new IPv6(ip.IPBytes);
}
}