Пример #1
0
        /// <summary>
        /// Returns all the IPs associated with the provided interface, if any, in
        /// textual form.
        /// </summary>
        /// <param name="strInterface">
        /// The name of the network interface or sub-interface to query
        /// (eg eth0 or eth0:0) or the string "default"
        /// </param>
        /// <param name="returnSubinterfaces">
        /// Whether to return IPs associated with subinterfaces of
        /// the given interface
        /// </param>
        /// <returns>
        /// A string vector of all the IPs associated with the provided
        /// interface. The local host IP is returned if the interface
        /// name "default" is specified or there is an I/O error looking
        /// for the given interface.
        /// </returns>
        /// <exception cref="UnknownHostException">If the given interface is invalid</exception>
        public static string[] GetIPs(string strInterface, bool returnSubinterfaces)
        {
            if ("default".Equals(strInterface))
            {
                return(new string[] { cachedHostAddress });
            }
            NetworkInterface netIf;

            try
            {
                netIf = NetworkInterface.GetByName(strInterface);
                if (netIf == null)
                {
                    netIf = GetSubinterface(strInterface);
                }
            }
            catch (SocketException e)
            {
                Log.Warn("I/O error finding interface " + strInterface + ": " + e.Message);
                return(new string[] { cachedHostAddress });
            }
            if (netIf == null)
            {
                throw new UnknownHostException("No such interface " + strInterface);
            }
            // NB: Using a LinkedHashSet to preserve the order for callers
            // that depend on a particular element being 1st in the array.
            // For example, getDefaultIP always returns the first element.
            LinkedHashSet <IPAddress> allAddrs = new LinkedHashSet <IPAddress>();

            Collections.AddAll(allAddrs, Collections.List(netIf.GetInetAddresses()));
            if (!returnSubinterfaces)
            {
                allAddrs.RemoveAll(GetSubinterfaceInetAddrs(netIf));
            }
            string[] ips = new string[allAddrs.Count];
            int      i   = 0;

            foreach (IPAddress addr in allAddrs)
            {
                ips[i++] = addr.GetHostAddress();
            }
            return(ips);
        }