コード例 #1
0
        } // NativeToHostEntry

        public static IPHostEntry GetHostByName(string hostName)
        {
            //
            // IPv6 disabled: use gethostbyname() to obtain DNS information.
            //
            IntPtr nativePointer =
                Interop.Winsock.gethostbyname(
                    hostName);

            if (nativePointer == IntPtr.Zero)
            {
                // Need to do this first since if we wait the last error code might be overwritten.
                SocketException socketException = new SocketException();

                IPAddress address;
                if (IPAddress.TryParse(hostName, out address))
                {
                    IPHostEntry ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
                    if (NetEventSource.Log.IsEnabled())
                    {
                        NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", ipHostEntry);
                    }
                    return(ipHostEntry);
                }

                throw socketException;
            }
            return(NativeToHostEntry(nativePointer));
        }
コード例 #2
0
        public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
        {
            Interop.Sys.HostEntry entry;
            int result = Interop.Sys.GetHostEntryForName(name, &entry);

            if (result != 0)
            {
                hostinfo        = NameResolutionUtilities.GetUnresolvedAnswer(name);
                nativeErrorCode = result;
                return(GetSocketErrorForNativeError(result));
            }

            try
            {
                string canonicalName = Marshal.PtrToStringAnsi((IntPtr)entry.CanonicalName);

                hostinfo = new IPHostEntry
                {
                    HostName    = string.IsNullOrEmpty(canonicalName) ? name : canonicalName,
                    Aliases     = Array.Empty <string>(),
                    AddressList = new IPAddress[entry.IPAddressCount]
                };

                void *addressListHandle = entry.AddressListHandle;
                var   nativeIPAddress   = default(Interop.Sys.IPAddress);
                for (int i = 0; i < entry.IPAddressCount; i++)
                {
                    int err = Interop.Sys.GetNextIPAddress(&addressListHandle, &nativeIPAddress);
                    Debug.Assert(err == 0);

                    IPAddress ipAddress;
                    if (nativeIPAddress.IsIPv6 == 0)
                    {
                        uint address = *(uint *)nativeIPAddress.Address;
                        ipAddress = new IPAddress((long)address);
                    }
                    else
                    {
                        byte[] address = new byte[Interop.Sys.NUM_BYTES_IN_IPV6_ADDRESS];
                        for (int b = 0; b < Interop.Sys.NUM_BYTES_IN_IPV6_ADDRESS; b++)
                        {
                            address[b] = nativeIPAddress.Address[b];
                        }

                        ipAddress = new IPAddress(address, (long)nativeIPAddress.ScopeId);
                    }

                    hostinfo.AddressList[i] = ipAddress;
                }
            }
            finally
            {
                Interop.Sys.FreeHostEntry(&entry);
            }

            nativeErrorCode = 0;
            return(SocketError.Success);
        }
コード例 #3
0
ファイル: DNS.cs プロジェクト: zuhuizou/corefx
        // Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical
        // If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the original address is returned.
        private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, AsyncCallback requestCallback, object state)
        {
            if (hostName == null)
            {
                throw new ArgumentNullException(nameof(hostName));
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("Dns.HostResolutionBeginHelper: " + hostName);
            }

            // See if it's an IP Address.
            IPAddress          address;
            ResolveAsyncResult asyncResult;

            if (IPAddress.TryParse(hostName, out address))
            {
                if ((address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)))
                {
                    throw new ArgumentException(SR.net_invalid_ip_addr, "hostNameOrAddress");
                }

                asyncResult = new ResolveAsyncResult(address, null, true, state, requestCallback);

                if (justReturnParsedIp)
                {
                    IPHostEntry hostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
                    asyncResult.StartPostingAsyncOp(false);
                    asyncResult.InvokeCallback(hostEntry);
                    asyncResult.FinishPostingAsyncOp();
                    return(asyncResult);
                }
            }
            else
            {
                asyncResult = new ResolveAsyncResult(hostName, null, true, state, requestCallback);
            }

            // Set up the context, possibly flow.
            asyncResult.StartPostingAsyncOp(false);

            // Start the resolve.
            Task.Factory.StartNew(
                s => ResolveCallback(s),
                asyncResult,
                CancellationToken.None,
                TaskCreationOptions.DenyChildAttach,
                TaskScheduler.Default);

            // Finish the flowing, maybe it completed?  This does nothing if we didn't initiate the flowing above.
            asyncResult.FinishPostingAsyncOp();
            return(asyncResult);
        }
コード例 #4
0
        public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
        {
            Interop.Sys.HostEntry entry;
            int result = Interop.Sys.GetHostEntryForName(name, &entry);

            if (result != 0)
            {
                hostinfo        = NameResolutionUtilities.GetUnresolvedAnswer(name);
                nativeErrorCode = result;
                return(GetSocketErrorForNativeError(result));
            }

            hostinfo = CreateIPHostEntry(entry);

            nativeErrorCode = 0;
            return(SocketError.Success);
        }
コード例 #5
0
ファイル: DNS.cs プロジェクト: vikas0380/corefx
        public static IPHostEntry Resolve(string hostName)
        {
            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "Resolve", hostName);
            }

            NameResolutionPal.EnsureSocketsAreInitialized();

            if (hostName == null)
            {
                throw new ArgumentNullException(nameof(hostName));
            }

            // See if it's an IP Address.
            IPAddress   address;
            IPHostEntry ipHostEntry;

            if (IPAddress.TryParse(hostName, out address) && (address.AddressFamily != AddressFamily.InterNetworkV6 || SocketProtocolSupportPal.OSSupportsIPv6))
            {
                try
                {
                    ipHostEntry = InternalGetHostByAddress(address, false);
                }
                catch (SocketException ex)
                {
                    if (NetEventSource.Log.IsEnabled())
                    {
                        NetEventSource.PrintError(NetEventSource.ComponentType.Socket, "DNS", "DNS.Resolve", ex.Message);
                    }

                    ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
                }
            }
            else
            {
                ipHostEntry = InternalGetHostByName(hostName, false);
            }

            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "Resolve", ipHostEntry);
            }
            return(ipHostEntry);
        }
コード例 #6
0
        public static IPHostEntry GetHostByName(string hostName)
        {
            NameResolutionPal.EnsureSocketsAreInitialized();

            if (hostName == null)
            {
                throw new ArgumentNullException(nameof(hostName));
            }

            // See if it's an IP Address.
            IPAddress address;

            if (IPAddress.TryParse(hostName, out address))
            {
                return(NameResolutionUtilities.GetUnresolvedAnswer(address));
            }
            return(InternalGetHostByName(hostName));
        }
コード例 #7
0
        public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
        {
            Interop.Sys.HostEntry entry;
            int result = Interop.Sys.GetHostEntryForName(name, &entry);

            if (result != 0)
            {
                hostinfo        = NameResolutionUtilities.GetUnresolvedAnswer(name);
                nativeErrorCode = result;
                return(GetSocketErrorForNativeError(result));
            }

            try
            {
                string canonicalName = Marshal.PtrToStringAnsi((IntPtr)entry.CanonicalName);

                hostinfo = new IPHostEntry
                {
                    HostName    = string.IsNullOrEmpty(canonicalName) ? name : canonicalName,
                    Aliases     = Array.Empty <string>(),
                    AddressList = new IPAddress[entry.IPAddressCount]
                };

                void *addressListHandle = entry.AddressListHandle;
                var   nativeIPAddress   = default(Interop.Sys.IPAddress);
                for (int i = 0; i < entry.IPAddressCount; i++)
                {
                    int err = Interop.Sys.GetNextIPAddress(&entry, &addressListHandle, &nativeIPAddress);
                    Debug.Assert(err == 0);

                    hostinfo.AddressList[i] = nativeIPAddress.GetIPAddress();
                }
            }
            finally
            {
                Interop.Sys.FreeHostEntry(&entry);
            }

            nativeErrorCode = 0;
            return(SocketError.Success);
        }
コード例 #8
0
        public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
        {
            if (name == "")
            {
                // To match documented behavior on Windows, if an empty string is passed in, use the local host's name.
                name = Dns.GetHostName();
            }

            Interop.Sys.HostEntry entry;
            int result = Interop.Sys.GetHostEntryForName(name, &entry);

            if (result != 0)
            {
                hostinfo        = NameResolutionUtilities.GetUnresolvedAnswer(name);
                nativeErrorCode = result;
                return(GetSocketErrorForNativeError(result));
            }

            hostinfo = CreateIPHostEntry(entry);

            nativeErrorCode = 0;
            return(SocketError.Success);
        }
コード例 #9
0
        public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
        {
            var hints = new Interop.libc.addrinfo
            {
                ai_family = Interop.libc.AF_UNSPEC, // Get all address families
                ai_flags  = Interop.libc.AI_CANONNAME
            };

            Interop.libc.addrinfo *addrinfo = null;
            string canonicalName            = null;

            IPAddress[] ipAddresses;
            try
            {
                int errorCode = Interop.libc.getaddrinfo(name, null, &hints, &addrinfo);
                if (errorCode != 0)
                {
                    hostinfo        = NameResolutionUtilities.GetUnresolvedAnswer(name);
                    nativeErrorCode = errorCode;
                    return(GetSocketErrorForNativeError(errorCode));
                }

                int numAddresses = 0;
                for (Interop.libc.addrinfo *ai = addrinfo; ai != null; ai = ai->ai_next)
                {
                    if (canonicalName == null && ai->ai_canonname != null)
                    {
                        canonicalName = Marshal.PtrToStringAnsi((IntPtr)ai->ai_canonname);
                    }

                    if ((ai->ai_family != Interop.libc.AF_INET) &&
                        (ai->ai_family != Interop.libc.AF_INET6 || !SocketProtocolSupportPal.OSSupportsIPv6))
                    {
                        continue;
                    }

                    numAddresses++;
                }

                if (numAddresses == 0)
                {
                    ipAddresses = Array.Empty <IPAddress>();
                }
                else
                {
                    ipAddresses = new IPAddress[numAddresses];
                    Interop.libc.addrinfo *ai = addrinfo;
                    for (int i = 0; i < numAddresses; ai = ai->ai_next)
                    {
                        Debug.Assert(ai != null);

                        if ((ai->ai_family != Interop.libc.AF_INET) &&
                            (ai->ai_family != Interop.libc.AF_INET6 || !SocketProtocolSupportPal.OSSupportsIPv6))
                        {
                            continue;
                        }

                        var sockaddr = new SocketAddress(
                            ai->ai_family == Interop.libc.AF_INET ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6,
                            checked ((int)ai->ai_addrlen));
                        for (int d = 0; d < ai->ai_addrlen; d++)
                        {
                            sockaddr[d] = ((byte *)ai->ai_addr)[d];
                        }

                        if (ai->ai_family == Interop.libc.AF_INET)
                        {
                            ipAddresses[i] = ((IPEndPoint)IPEndPointStatics.Any.Create(sockaddr)).Address;
                        }
                        else
                        {
                            ipAddresses[i] = ((IPEndPoint)IPEndPointStatics.IPv6Any.Create(sockaddr)).Address;
                        }

                        i++;
                    }
                }
            }
            finally
            {
                if (addrinfo != null)
                {
                    Interop.libc.freeaddrinfo(addrinfo);
                }
            }

            hostinfo = new IPHostEntry
            {
                HostName    = canonicalName ?? name,
                Aliases     = Array.Empty <string>(),
                AddressList = ipAddresses
            };
            nativeErrorCode = 0;
            return(SocketError.Success);
        }
コード例 #10
0
        public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
        {
            //
            // Use SocketException here to show operation not supported
            // if, by some nefarious means, this method is called on an
            // unsupported platform.
            //
            SafeFreeAddrInfo root = null;
            var    addresses      = new List <IPAddress>();
            string canonicalname  = null;

            AddressInfo hints = new AddressInfo();

            hints.ai_flags  = AddressInfoHints.AI_CANONNAME;
            hints.ai_family = AddressFamily.Unspecified;   // gets all address families

            nativeErrorCode = 0;

            //
            // Use try / finally so we always get a shot at freeaddrinfo
            //
            try
            {
                SocketError errorCode = (SocketError)SafeFreeAddrInfo.GetAddrInfo(name, null, ref hints, out root);
                if (errorCode != SocketError.Success)
                { // Should not throw, return mostly blank hostentry
                    hostinfo = NameResolutionUtilities.GetUnresolvedAnswer(name);
                    return(errorCode);
                }

                AddressInfo *pAddressInfo = (AddressInfo *)root.DangerousGetHandle();
                //
                // Process the results
                //
                while (pAddressInfo != null)
                {
                    SocketAddress sockaddr;
                    //
                    // Retrieve the canonical name for the host - only appears in the first AddressInfo
                    // entry in the returned array.
                    //
                    if (canonicalname == null && pAddressInfo->ai_canonname != null)
                    {
                        canonicalname = Marshal.PtrToStringUni((IntPtr)pAddressInfo->ai_canonname);
                    }
                    //
                    // Only process IPv4 or IPv6 Addresses. Note that it's unlikely that we'll
                    // ever get any other address families, but better to be safe than sorry.
                    // We also filter based on whether IPv6 is supported on the current
                    // platform / machine.
                    //
                    if ((pAddressInfo->ai_family == AddressFamily.InterNetwork) || // Never filter v4
                        (pAddressInfo->ai_family == AddressFamily.InterNetworkV6 && SocketProtocolSupportPal.OSSupportsIPv6))
                    {
                        sockaddr = new SocketAddress(pAddressInfo->ai_family, pAddressInfo->ai_addrlen);
                        //
                        // Push address data into the socket address buffer
                        //
                        for (int d = 0; d < pAddressInfo->ai_addrlen; d++)
                        {
                            sockaddr[d] = *(pAddressInfo->ai_addr + d);
                        }
                        //
                        // NOTE: We need an IPAddress now, the only way to create it from a
                        //       SocketAddress is via IPEndPoint. This ought to be simpler.
                        //
                        if (pAddressInfo->ai_family == AddressFamily.InterNetwork)
                        {
                            addresses.Add(((IPEndPoint)IPEndPointStatics.Any.Create(sockaddr)).Address);
                        }
                        else
                        {
                            addresses.Add(((IPEndPoint)IPEndPointStatics.IPv6Any.Create(sockaddr)).Address);
                        }
                    }
                    //
                    // Next addressinfo entry
                    //
                    pAddressInfo = pAddressInfo->ai_next;
                }
            }
            finally
            {
                if (root != null)
                {
                    root.Dispose();
                }
            }

            //
            // Finally, put together the IPHostEntry
            //
            hostinfo = new IPHostEntry();

            hostinfo.HostName    = canonicalname != null ? canonicalname : name;
            hostinfo.Aliases     = Array.Empty <string>();
            hostinfo.AddressList = addresses.ToArray();

            return(SocketError.Success);
        }
コード例 #11
0
        // Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical
        // If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the original address is returned.
        private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, bool throwOnIIPAny, AsyncCallback requestCallback, object state)
        {
            if (hostName == null)
            {
                throw new ArgumentNullException(nameof(hostName));
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(null, hostName);
            }

            // See if it's an IP Address.
            IPAddress             ipAddress;
            DnsResolveAsyncResult asyncResult;

            if (IPAddress.TryParse(hostName, out ipAddress))
            {
                if (throwOnIIPAny && (ipAddress.Equals(IPAddress.Any) || ipAddress.Equals(IPAddress.IPv6Any)))
                {
                    throw new ArgumentException(SR.net_invalid_ip_addr, nameof(hostName));
                }

                asyncResult = new DnsResolveAsyncResult(ipAddress, null, state, requestCallback);

                if (justReturnParsedIp)
                {
                    IPHostEntry hostEntry = NameResolutionUtilities.GetUnresolvedAnswer(ipAddress);
                    asyncResult.StartPostingAsyncOp(false);
                    asyncResult.InvokeCallback(hostEntry);
                    asyncResult.FinishPostingAsyncOp();
                    return(asyncResult);
                }
            }
            else
            {
                asyncResult = new DnsResolveAsyncResult(hostName, null, state, requestCallback);
            }

            // Set up the context, possibly flow.
            asyncResult.StartPostingAsyncOp(false);

            // If the OS supports it and 'hostName' is not an IP Address, resolve the name asynchronously
            // instead of calling the synchronous version in the ThreadPool.
            if (NameResolutionPal.SupportsGetAddrInfoAsync && ipAddress == null)
            {
                ValidateHostName(hostName);
                NameResolutionPal.GetAddrInfoAsync(asyncResult);
            }
            else
            {
                // Start the resolve.
                Task.Factory.StartNew(
                    s => ResolveCallback(s),
                    asyncResult,
                    CancellationToken.None,
                    TaskCreationOptions.DenyChildAttach,
                    TaskScheduler.Default);
            }

            // Finish the flowing, maybe it completed?  This does nothing if we didn't initiate the flowing above.
            asyncResult.FinishPostingAsyncOp();
            return(asyncResult);
        }
コード例 #12
0
        public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
        {
            Interop.Sys.HostEntry *entry = null;
            int result = Interop.Sys.GetHostEntriesForName(name, &entry);

            if (result != 0)
            {
                hostinfo        = NameResolutionUtilities.GetUnresolvedAnswer(name);
                nativeErrorCode = result;
                return(GetSocketErrorForNativeError(result));
            }

            try
            {
                string canonicalName = Marshal.PtrToStringAnsi((IntPtr)entry->CanonicalName);

                hostinfo = new IPHostEntry
                {
                    HostName    = string.IsNullOrEmpty(canonicalName) ? name : canonicalName,
                    Aliases     = Array.Empty <string>(),
                    AddressList = new IPAddress[entry->Count]
                };

                // Clean this up when fixing #3570
                var buffer = new byte[SocketAddressPal.IPv6AddressSize];
                for (int i = 0; i < entry->Count; i++)
                {
                    SocketAddress sockaddr;
                    IPEndPoint    factory;
                    int           bufferLength;
                    if (entry->Addresses[i].IsIpv6)
                    {
                        sockaddr     = new SocketAddress(AddressFamily.InterNetworkV6);
                        factory      = IPEndPointStatics.IPv6Any;
                        bufferLength = SocketAddressPal.IPv6AddressSize;

                        SocketAddressPal.SetAddressFamily(buffer, AddressFamily.InterNetworkV6);
                        SocketAddressPal.SetIPv6Address(buffer, entry->Addresses[i].Address, entry->Addresses[i].Count, 0);
                        SocketAddressPal.SetPort(buffer, 0);
                    }
                    else
                    {
                        sockaddr     = new SocketAddress(AddressFamily.InterNetwork);
                        factory      = IPEndPointStatics.Any;
                        bufferLength = SocketAddressPal.IPv4AddressSize;

                        SocketAddressPal.SetAddressFamily(buffer, AddressFamily.InterNetwork);
                        SocketAddressPal.SetIPv4Address(buffer, entry->Addresses[i].Address);
                        SocketAddressPal.SetPort(buffer, 0);
                    }

                    for (int d = 0; d < bufferLength; d++)
                    {
                        sockaddr[d] = buffer[d];
                    }

                    hostinfo.AddressList[i] = ((IPEndPoint)factory.Create(sockaddr)).Address;
                }
            }
            finally
            {
                Interop.Sys.FreeHostEntriesForName(entry);
            }

            nativeErrorCode = 0;
            return(SocketError.Success);
        }