System.Net.NameResolutionPal.EnsureSocketsAreInitialized C# (CSharp) Method

EnsureSocketsAreInitialized() public static method

public static EnsureSocketsAreInitialized ( ) : void
return void
        public static void EnsureSocketsAreInitialized()
        {
            if (!Volatile.Read(ref s_initialized))
            {
                lock (s_initializedLock)
                {
                    if (!s_initialized)
                    {
                        Interop.Winsock.WSAData wsaData = new Interop.Winsock.WSAData();

                        SocketError errorCode =
                            Interop.Winsock.WSAStartup(
                                (short)0x0202, // we need 2.2
                                out wsaData);

                        if (errorCode != SocketError.Success)
                        {
                            //
                            // failed to initialize, throw
                            //
                            // WSAStartup does not set LastWin32Error
                            throw new SocketException((int)errorCode);
                        }

                        Volatile.Write(ref s_initialized, true);
                    }
                }
            }
        }
    }

Usage Example

Example #1
0
        public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
            }
            NameResolutionPal.EnsureSocketsAreInitialized();

            if (hostNameOrAddress is null)
            {
                throw new ArgumentNullException(nameof(hostNameOrAddress));
            }

            // See if it's an IP Address.
            IPAddress[] addresses;
            if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address))
            {
                if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
                {
                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Error(address, $"Invalid address '{address}'");
                    }
                    throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(hostNameOrAddress)));
                }

                addresses = new IPAddress[] { address };
            }
            else
            {
                addresses = GetHostAddressesCore(hostNameOrAddress);
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Exit(hostNameOrAddress, addresses);
            }
            return(addresses);
        }
All Usage Examples Of System.Net.NameResolutionPal::EnsureSocketsAreInitialized