< Summary

Line coverage
0%
Covered lines: 0
Uncovered lines: 133
Coverable lines: 133
Total lines: 328
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 76
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

File(s)

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs

#LineLine coverage
 1// Licensed to the .NET Foundation under one or more agreements.
 2// The .NET Foundation licenses this file to you under the MIT license.
 3
 4using System.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Globalization;
 7using System.Net.Sockets;
 8using System.Numerics;
 9using System.Runtime.InteropServices;
 10using System.Text.Unicode;
 11
 12namespace System.Net
 13{
 14    /// <summary>
 15    /// Provides an IP address.
 16    /// </summary>
 17    public class IPEndPoint : EndPoint, ISpanFormattable, ISpanParsable<IPEndPoint>, IUtf8SpanFormattable, IUtf8SpanPars
 18    {
 19        /// <summary>
 20        /// Specifies the minimum acceptable value for the <see cref='System.Net.IPEndPoint.Port'/> property.
 21        /// </summary>
 22        public const int MinPort = 0x00000000;
 23
 24        /// <summary>
 25        /// Specifies the maximum acceptable value for the <see cref='System.Net.IPEndPoint.Port'/> property.
 26        /// </summary>
 27        public const int MaxPort = 0x0000FFFF;
 28
 29        private IPAddress _address;
 30        private int _port;
 31
 032        public override AddressFamily AddressFamily => _address.AddressFamily;
 33
 34        /// <summary>
 35        /// Creates a new instance of the IPEndPoint class with the specified address and port.
 36        /// </summary>
 037        public IPEndPoint(long address, int port)
 038        {
 039            if (!TcpValidationHelpers.ValidatePortNumber(port))
 040            {
 041                throw new ArgumentOutOfRangeException(nameof(port));
 42            }
 43
 044            _port = port;
 045            _address = new IPAddress(address);
 046        }
 47
 48        /// <summary>
 49        /// Creates a new instance of the IPEndPoint class with the specified address and port.
 50        /// </summary>
 051        public IPEndPoint(IPAddress address, int port)
 052        {
 053            ArgumentNullException.ThrowIfNull(address);
 54
 055            if (!TcpValidationHelpers.ValidatePortNumber(port))
 056            {
 057                throw new ArgumentOutOfRangeException(nameof(port));
 58            }
 59
 060            _port = port;
 061            _address = address;
 062        }
 63
 64        /// <summary>
 65        /// Gets or sets the IP address.
 66        /// </summary>
 67        public IPAddress Address
 68        {
 069            get => _address;
 70            set
 071            {
 072                ArgumentNullException.ThrowIfNull(value);
 073                _address = value;
 074            }
 75        }
 76
 77        /// <summary>
 78        /// Gets or sets the port.
 79        /// </summary>
 80        public int Port
 81        {
 082            get => _port;
 83            set
 084            {
 085                if (!TcpValidationHelpers.ValidatePortNumber(value))
 086                {
 087                    throw new ArgumentOutOfRangeException(nameof(value));
 88                }
 89
 090                _port = value;
 091            }
 92        }
 93
 94        public static bool TryParse(string s, [NotNullWhen(true)] out IPEndPoint? result)
 095        {
 096            return TryParse(s.AsSpan(), out result);
 097        }
 98
 99        internal static bool InternalTryParse<TChar>(ReadOnlySpan<TChar> s, [NotNullWhen(true)] out IPEndPoint? result)
 100            where TChar : unmanaged, IBinaryInteger<TChar>
 0101        {
 0102            Debug.Assert(typeof(TChar) == typeof(byte) || typeof(TChar) == typeof(char));
 103
 0104            int addressLength = s.Length;  // If there's no port then send the entire string to the address parser
 0105            int lastColonPos = s.LastIndexOf(TChar.CreateTruncating(':'));
 106
 107            // Look to see if this is an IPv6 address with a port.
 0108            if (lastColonPos > 0)
 0109            {
 0110                if (s[lastColonPos - 1] == TChar.CreateTruncating(']'))
 0111                {
 0112                    addressLength = lastColonPos;
 0113                }
 114                // Look to see if this is IPv4 with a port (IPv6 will have another colon)
 0115                else if (s.Slice(0, lastColonPos).LastIndexOf(TChar.CreateTruncating(':')) == -1)
 0116                {
 0117                    addressLength = lastColonPos;
 0118                }
 0119            }
 120
 0121            IPAddress? address = IPAddressParser.Parse(s.Slice(0, addressLength), true);
 0122            if (address is not null)
 0123            {
 0124                if (addressLength == s.Length)
 0125                {
 0126                    result = new IPEndPoint(address, 0);
 0127                    return true;
 128                }
 129                else
 0130                {
 131                    uint port;
 0132                    ReadOnlySpan<TChar> portSpan = s.Slice(addressLength + 1);
 133                    bool isConvertedToInt;
 134
 0135                    if (typeof(TChar) == typeof(byte))
 0136                    {
 0137                        isConvertedToInt = uint.TryParse(MemoryMarshal.Cast<TChar, byte>(portSpan), NumberStyles.None, C
 0138                    }
 139                    else
 0140                    {
 0141                        isConvertedToInt = uint.TryParse(MemoryMarshal.Cast<TChar, char>(portSpan), NumberStyles.None, C
 0142                    }
 143
 0144                    if (isConvertedToInt && port <= MaxPort)
 0145                    {
 0146                        result = new IPEndPoint(address, (int)port);
 0147                        return true;
 148                    }
 0149                }
 0150            }
 151
 0152            result = null;
 0153            return false;
 0154        }
 155
 156        /// <summary>Tries to convert the character span to its <see cref="IPEndPoint"/> equivalent.</summary>
 157        /// <param name="s">A span container the characters representing the <see cref="IPEndPoint"/> to convert.</param
 158        /// <param name="result">When this method returns, contains the <see cref="IPEndPoint"/> value equivalent to wha
 159        /// <returns><c>true</c> if <paramref name="s" /> was converted successfully; otherwise, false.</returns>
 0160        public static bool TryParse(ReadOnlySpan<char> s, [NotNullWhen(true)] out IPEndPoint? result) => InternalTryPars
 161
 162        public static IPEndPoint Parse(string s)
 0163        {
 0164            ArgumentNullException.ThrowIfNull(s);
 165
 0166            return Parse(s.AsSpan());
 0167        }
 168
 169        public static IPEndPoint Parse(ReadOnlySpan<char> s)
 0170        {
 0171            if (TryParse(s, out IPEndPoint? result))
 0172            {
 0173                return result;
 174            }
 175
 0176            throw new FormatException(SR.bad_endpoint_string);
 0177        }
 178
 179        public override string ToString() =>
 0180            _address.AddressFamily == AddressFamily.InterNetworkV6 ?
 0181                string.Create(NumberFormatInfo.InvariantInfo, $"[{_address}]:{_port}") :
 0182                string.Create(NumberFormatInfo.InvariantInfo, $"{_address}:{_port}");
 183
 0184        public override SocketAddress Serialize() => new SocketAddress(Address, Port);
 185
 186        public override EndPoint Create(SocketAddress socketAddress)
 0187        {
 0188            ArgumentNullException.ThrowIfNull(socketAddress);
 189
 0190            if (socketAddress.Family is not (AddressFamily.InterNetwork or AddressFamily.InterNetworkV6))
 0191            {
 0192                throw new ArgumentException(SR.Format(SR.net_InvalidAddressFamily, socketAddress.Family.ToString(), GetT
 193            }
 194
 0195            int minSize = AddressFamily == AddressFamily.InterNetworkV6 ? SocketAddress.IPv6AddressSize : SocketAddress.
 0196            if (socketAddress.Size < minSize)
 0197            {
 0198                throw new ArgumentException(SR.Format(SR.net_InvalidSocketAddressSize, socketAddress.GetType().FullName,
 199            }
 200
 0201            return socketAddress.GetIPEndPoint();
 0202        }
 203
 204        public override bool Equals([NotNullWhen(true)] object? comparand)
 0205        {
 0206            return comparand is IPEndPoint other && other._address.Equals(_address) && other._port == _port;
 0207        }
 208
 209        public override int GetHashCode()
 0210        {
 0211            return _address.GetHashCode() ^ _port;
 0212        }
 213
 214        /// <summary>Converts the UTF-8 span to its <see cref="IPEndPoint"/> equivalent.</summary>
 215        /// <param name="utf8Text">A span containing the characters representing the <see cref="IPEndPoint"/> to convert
 216        /// <returns>contains the <see cref="IPEndPoint"/> value equivalent to what is contained in <paramref name="utf8
 217        /// <exception cref="FormatException"><paramref name="utf8Text"/> is invalid</exception>
 218        public static IPEndPoint Parse(ReadOnlySpan<byte> utf8Text)
 0219        {
 0220            if (TryParse(utf8Text, out IPEndPoint? result))
 0221            {
 0222                return result;
 223            }
 224
 0225            throw new FormatException(SR.bad_endpoint_string);
 0226        }
 227
 228        /// <summary>Converts the character span to its <see cref="IPEndPoint"/> equivalent.</summary>
 229        /// <param name="s">A span containing the characters representing the <see cref="IPEndPoint"/> to convert.</para
 230        /// <param name="provider">An object that provides culture-specific formatting information about <paramref name=
 231        /// <returns>contains the <see cref="IPEndPoint"/> value equivalent to what is contained in <paramref name="s" /
 232        /// <exception cref="FormatException"><paramref name="s"/> is invalid</exception>
 0233        static IPEndPoint ISpanParsable<IPEndPoint>.Parse(ReadOnlySpan<char> s, IFormatProvider? provider) => Parse(s);
 234
 235        /// <summary>Converts the string to its <see cref="IPEndPoint"/> equivalent.</summary>
 236        /// <param name="s">A string containing the characters representing the <see cref="IPEndPoint"/> to convert.</pa
 237        /// <param name="provider">An object that provides culture-specific formatting information about <paramref name=
 238        /// <returns>contains the <see cref="IPEndPoint"/> value equivalent to what is contained in <paramref name="s" /
 239        /// <exception cref="FormatException"><paramref name="s"/> is invalid</exception>
 0240        static IPEndPoint IParsable<IPEndPoint>.Parse(string s, IFormatProvider? provider) => Parse(s);
 241
 242        /// <summary>Converts the UTF-8 span to its <see cref="IPEndPoint"/> equivalent.</summary>
 243        /// <param name="utf8Text">A Span containing the UTF-8 characters representing the <see cref="IPEndPoint"/> to c
 244        /// <param name="provider">An object that provides culture-specific formatting information about <paramref name=
 245        /// <returns>contains the <see cref="IPEndPoint"/> value equivalent to what is contained in <paramref name="utf8
 246        /// <exception cref="FormatException"><paramref name="utf8Text"/> is invalid</exception>
 0247        static IPEndPoint IUtf8SpanParsable<IPEndPoint>.Parse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider) =>
 248
 249        /// <summary>Tries to convert the UTF-8 span to its <see cref="IPEndPoint"/> equivalent.</summary>
 250        /// <param name="utf8Text">A span containing the UTF-8 characters representing the <see cref="IPEndPoint"/> to c
 251        /// <param name="result">When this method returns, contains the <see cref="IPEndPoint"/> value equivalent to wha
 252        /// <returns><c>true</c> if <paramref name="utf8Text" /> was converted successfully; otherwise, false.</returns>
 0253        public static bool TryParse(ReadOnlySpan<byte> utf8Text, [NotNullWhen(true)] out IPEndPoint? result) => Internal
 254
 255        /// <summary>Tries to convert the character span to its <see cref="IPEndPoint"/> equivalent.</summary>
 256        /// <param name="s">A span container the characters representing the <see cref="IPEndPoint"/> to convert.</param
 257        /// <param name="provider">An object that provides culture-specific formatting information about <paramref name=
 258        /// <param name="result">When this method returns, contains the <see cref="IPEndPoint"/> value equivalent to wha
 259        /// <returns><c>true</c> if <paramref name="s" /> was converted successfully; otherwise, false.</returns>
 0260        static bool ISpanParsable<IPEndPoint>.TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, [NotNullWhen(tru
 261
 262        /// <summary>Tries to convert the string to its <see cref="IPEndPoint"/> equivalent.</summary>
 263        /// <param name="s">A string representing the <see cref="IPEndPoint"/> to convert.</param>
 264        /// <param name="provider">An object that provides culture-specific formatting information about <paramref name=
 265        /// <param name="result">When this method returns, contains the <see cref="IPEndPoint"/> value equivalent to wha
 266        /// <returns><c>true</c> if <paramref name="s" /> was converted successfully; otherwise, false.</returns>
 267        static bool IParsable<IPEndPoint>.TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [NotNullWhe
 0268        {
 0269            if (s is null)
 0270            {
 0271                result = default;
 0272                return false;
 273            }
 274
 0275            return TryParse(s, out result);
 0276        }
 277
 278        /// <summary>Tries to convert the UTF-8 span to its <see cref="IPEndPoint"/> equivalent.</summary>
 279        /// <param name="utf8Text">A span container the characters representing the <see cref="IPEndPoint"/> to convert.
 280        /// <param name="provider">An object that provides culture-specific formatting information about <paramref name=
 281        /// <param name="result">When this method returns, contains the <see cref="IPEndPoint"/> value equivalent to wha
 282        /// <returns><c>true</c> if <paramref name="utf8Text" /> was converted successfully; otherwise, false.</returns>
 0283        static bool IUtf8SpanParsable<IPEndPoint>.TryParse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, [NotN
 284
 285        /// <summary>Returns the string representation of the current instance using the specified format string to defi
 286        /// <param name="format">A standard or custom numeric format string that defines the format of individual elemen
 287        /// <param name="formatProvider">A format provider that supplies culture-specific formatting information.</param
 288        /// <returns>The string representation of the current instance.</returns>
 0289        string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => ToString();
 290
 291        /// <summary>Tries to format the value of the current instance as characters into the provided span of character
 292        /// <param name="destination">When this method returns, this parameter is filled with this instance formatted ch
 293        /// <param name="charsWritten">When this method returns, the number of bytes that were written in <paramref name
 294        /// <returns><see langword="true"/> if the formatting was successful; otherwise, <see langword="false"/>.</retur
 295        public bool TryFormat(Span<char> destination, out int charsWritten) =>
 0296            _address.AddressFamily == AddressFamily.InterNetworkV6 ?
 0297                destination.TryWrite(CultureInfo.InvariantCulture, $"[{_address}]:{_port}", out charsWritten) :
 0298                destination.TryWrite(CultureInfo.InvariantCulture, $"{_address}:{_port}", out charsWritten);
 299
 300        /// <summary>Tries to format the value of the current instance as UTF-8 bytes into the provided span.</summary>
 301        /// <param name="utf8Destination">When this method returns, this parameter is filled with this instance formatte
 302        /// <param name="bytesWritten">When this method returns, the number of bytes that were written in <paramref name
 303        /// <returns><see langword="true"/> if the formatting was successful; otherwise, <see langword="false"/>.</retur
 304        public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten) =>
 0305            _address.AddressFamily == AddressFamily.InterNetworkV6 ?
 0306                Utf8.TryWrite(utf8Destination, CultureInfo.InvariantCulture, $"[{_address}]:{_port}", out bytesWritten) 
 0307                Utf8.TryWrite(utf8Destination, CultureInfo.InvariantCulture, $"{_address}:{_port}", out bytesWritten);
 308
 309        /// <summary>Tries to format the value of the current instance as characters into the provided span of character
 310        /// <param name="destination">When this method returns, this parameter is filled with this instance formatted ch
 311        /// <param name="charsWritten">When this method returns, the number of bytes that were written in <paramref name
 312        /// <param name="format">A span containing the characters that represent a standard or custom format string that
 313        /// <param name="provider">An optional object that supplies culture-specific formatting information for <paramre
 314        /// <returns><see langword="true"/> if the formatting was successful; otherwise, <see langword="false"/>.</retur
 315        bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormat
 0316            TryFormat(destination, out charsWritten);
 317
 318        /// <summary>Tries to format the value of the current instance as UTF-8 bytes into the provided span.</summary>
 319        /// <param name="utf8Destination">When this method returns, this parameter is filled with this instance formatte
 320        /// <param name="bytesWritten">When this method returns, the number of bytes that were written in <paramref name
 321        /// <param name="format">A span containing the characters that represent a standard or custom format string that
 322        /// <param name="provider">An optional object that supplies culture-specific formatting information for <paramre
 323        /// <returns><see langword="true"/> if the formatting was successful; otherwise, <see langword="false"/>.</retur
 324        bool IUtf8SpanFormattable.TryFormat(Span<byte> utf8Destination, out int bytesWritten, ReadOnlySpan<char> format,
 0325            TryFormat(utf8Destination, out bytesWritten);
 326    }
 327}
 328

Methods/Properties

AddressFamily()
.ctor(System.Int64,System.Int32)
.ctor(System.Net.IPAddress,System.Int32)
Address()
Address(System.Net.IPAddress)
Port()
Port(System.Int32)
TryParse(System.String,System.Net.IPEndPoint&)
InternalTryParse(System.ReadOnlySpan`1<TChar>,System.Net.IPEndPoint&)
TryParse(System.ReadOnlySpan`1<System.Char>,System.Net.IPEndPoint&)
Parse(System.String)
Parse(System.ReadOnlySpan`1<System.Char>)
ToString()
Serialize()
Create(System.Net.SocketAddress)
Equals(System.Object)
GetHashCode()
Parse(System.ReadOnlySpan`1<System.Byte>)
System.ISpanParsable<System.Net.IPEndPoint>.Parse(System.ReadOnlySpan`1<System.Char>,System.IFormatProvider)
System.IParsable<System.Net.IPEndPoint>.Parse(System.String,System.IFormatProvider)
System.IUtf8SpanParsable<System.Net.IPEndPoint>.Parse(System.ReadOnlySpan`1<System.Byte>,System.IFormatProvider)
TryParse(System.ReadOnlySpan`1<System.Byte>,System.Net.IPEndPoint&)
System.ISpanParsable<System.Net.IPEndPoint>.TryParse(System.ReadOnlySpan`1<System.Char>,System.IFormatProvider,System.Net.IPEndPoint&)
System.IParsable<System.Net.IPEndPoint>.TryParse(System.String,System.IFormatProvider,System.Net.IPEndPoint&)
System.IUtf8SpanParsable<System.Net.IPEndPoint>.TryParse(System.ReadOnlySpan`1<System.Byte>,System.IFormatProvider,System.Net.IPEndPoint&)
System.IFormattable.ToString(System.String,System.IFormatProvider)
TryFormat(System.Span`1<System.Char>,System.Int32&)
TryFormat(System.Span`1<System.Byte>,System.Int32&)
System.ISpanFormattable.TryFormat(System.Span`1<System.Char>,System.Int32&,System.ReadOnlySpan`1<System.Char>,System.IFormatProvider)
System.IUtf8SpanFormattable.TryFormat(System.Span`1<System.Byte>,System.Int32&,System.ReadOnlySpan`1<System.Char>,System.IFormatProvider)