Ejemplo n.º 1
0
 public Client(NetworkInterface networkInterface)
 {
     network_interface_info = NetworkInterfaceInfo.GetNetworkInterfaceInfo(networkInterface);
     service_cache          = new ServiceCache(this);
     notify_listener        = new NotifyListener(this);
     browsers = new Dictionary <string, Browser> ();
 }
Ejemplo n.º 2
0
 public Server(string defaultLocation, NetworkInterface networkInterface)
 {
     default_location       = defaultLocation;
     network_interface_info = NetworkInterfaceInfo.GetNetworkInterfaceInfo(networkInterface);
     request_listener       = new RequestListener(this);
     announcers             = new Dictionary <string, Announcer> ();
 }
Ejemplo n.º 3
0
 public PcapNgFileOutput(NetworkInterfaceInfo nic, string filename)
 {
     this.nic        = nic;
     this.fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None);
     this.writer     = new BinaryWriter(this.fileStream);
     this.WriteHeader();
 }
Ejemplo n.º 4
0
        private static void Main(string[] args)
        {
            // You can only create raw sockets with elevated privileges
            if (!UserInformation.IsAdmin())
            {
                var message = SystemInformation.IsWindows
                    ? "Please run with elevated prilileges"
                    : "Please run using sudo";

                Console.WriteLine(message);
                Environment.Exit(1);
            }

            var appOptions = ParseCommandLine(args);

            if (appOptions.ShowHelp)
            {
                ShowHelp(appOptions);
                Environment.Exit(0);
            }

            var nics = NetworkInterfaceInfo.GetInterfaces();

            if (!appOptions.InterfaceId.HasValue ||
                appOptions.InterfaceId > nics.Count - 1 ||
                appOptions.InterfaceId < 0)
            {
                Console.WriteLine("Invalid interface ID");
                ShowHelp(appOptions);
                Environment.Exit(3);
            }

            var filters = appOptions.BuildFilters();
            var nic     = nics[appOptions.InterfaceId !.Value];
Ejemplo n.º 5
0
        private void updateStatus()
        {
            NetworkInterfaceList networkInterfaceList = new NetworkInterfaceList();
            NetworkInterfaceInfo wifiInfo             = null;

            foreach (NetworkInterfaceInfo netInfo in networkInterfaceList)
            {
                if (netInfo.InterfaceSubtype == NetworkInterfaceSubType.WiFi && netInfo.InterfaceState == ConnectState.Connected)
                {
                    wifiInfo = netInfo;
                    break;
                }
            }
            if (wifiInfo != null)
            {
                Name = wifiInfo.InterfaceName;
            }
            else
            {
                Name = "";
            }
            if (wifiTextBlock != null)
            {
                wifiTextBlock.Text = Name;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="InterfaceGuid">The GUID of the network adapter.</param>
        /// <exception cref="NetworkInformationException"/>
        /// <exception cref="ArgumentNullException"/>
        /// <exception cref="FormatException"/>
        /// <returns>NetworkInterfaceInfo</returns>
        internal static NetworkInterfaceInfo GetNetworkInterfaceInformation(Guid InterfaceGuid)
        {
            NetworkInterfaceInfo NetITFInfo = new NetworkInterfaceInfo();

            foreach (NetworkInterface NetITF in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (!InterfaceGuid.Equals(Guid.Parse(NetITF.Id)))
                {
                    continue;
                }
                IPInterfaceProperties IPITFProps = NetITF.GetIPProperties();
                foreach (UnicastIPAddressInformation uIPAddrInfo in IPITFProps.UnicastAddresses)
                {
                    if (!uIPAddrInfo.Address.IsIPv6LinkLocal && !uIPAddrInfo.Address.IsIPv6Teredo)
                    {
                        NetITFInfo.DeviceDescription = NetITF.Description;
                        NetITFInfo.DeviceName        = NetITF.Name;
                        NetITFInfo.IPAddress         = uIPAddrInfo.Address;
                        NetITFInfo.PhysicalAddress   = NetITF.GetPhysicalAddress();
                        NetITFInfo.GatewayAddress    = IPITFProps.GatewayAddresses.Count > 0 ?
                                                       IPITFProps.GatewayAddresses[0].Address : IPAddress.None;
                        return(NetITFInfo);
                    }
                }
            }
            return(NetITFInfo);
        }
Ejemplo n.º 7
0
 public PcapNgFileOutput(NetworkInterfaceInfo nic, string filename)
 {
     this.nic = nic;
     this.fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None);
     this.writer = new BinaryWriter(fileStream);
     this.WriteHeader();
 }
Ejemplo n.º 8
0
        private static void NetworkInformationCallback(NetworkInterfaceInfo netInfo)
        {
            // set encoding behavior based on speed of network: wifi networks don't need encoding,
            // but cellular networks do
            string encString;

            if (IsSlowNetwork(netInfo))
            {
                encode    = true;
                encString = "application/speex";
            }
            else
            {
                encode    = false;
                encString = "application/pcm";
            }

            // initialize the encoding
            encoding = String.Format("{0}-{1}-{2}-{3}",
                                     encString,
                                     mic.SampleRate,
                                     "16",                                  // 16 bits per sample
                                     ((int)AudioChannels.Mono).ToString()); // 1 audio channel (mono)

            // Trace the operation
            TraceHelper.AddMessage("POST: " + encoding);

            // send the HTTP POST to initialize the speech operation
            // upon completion it will invoke the StartMic delegate to start the microphone
            NetworkHelper.SendPost(
                user,
                "Zaplify-Speech-Encoding: " + encoding,
                new StartMicDelegate(StartMic),
                new NetworkDelegate(NetworkCallback));
        }
Ejemplo n.º 9
0
        public int getStatisticsNetType()
        {
            NetworkInterfaceList interfaceList = new NetworkInterfaceList();
            NetworkInterfaceInfo interfaceInfo = interfaceList.First();

            switch (interfaceInfo.InterfaceSubtype)
            {
            case NetworkInterfaceSubType.Cellular_3G:
            case NetworkInterfaceSubType.Cellular_EVDO:
            case NetworkInterfaceSubType.Cellular_EVDV:
            case NetworkInterfaceSubType.Cellular_HSPA:
                return(NETTYPE_3G);

            case NetworkInterfaceSubType.Cellular_GPRS:
            case NetworkInterfaceSubType.Cellular_EDGE:
            case NetworkInterfaceSubType.Cellular_1XRTT:
                return(NETTYPE_2G);

            case NetworkInterfaceSubType.Cellular_EHRPD:
            case NetworkInterfaceSubType.Cellular_LTE:
                return(NETTYPE_4G);

            case NetworkInterfaceSubType.WiFi:
                return(NETTYPE_WIFI);

            default:
                return(NETTYPE_NON);
            }
        }
Ejemplo n.º 10
0
        public void Start()
        {
            var conn    = ConnectionPicker.GetGameConnections(ProcessWorking);
            var filters = FilterBuilder.BuildDefaultFilter(conn);
            var nic     = NetworkInterfaceInfo.GetDefaultInterface();

            Start(nic.IPAddress, filters);
        }
Ejemplo n.º 11
0
        private static void StartSniffing(NetworkInterfaceInfo nic, out PcapNgFileOutput output, out SocketSniffer sniffer)
        {
            var appOptions = new AppOptions();

            appOptions.Parse(new string[] { "" });
            var filters = appOptions.BuildFilters();

            output  = new PcapNgFileOutput(nic, appOptions.Filename);
            sniffer = new SocketSniffer(nic, filters, output);
            sniffer.Start();
        }
Ejemplo n.º 12
0
        public CurWifiInfo getCurWifiInfo()
        {
            CurWifiInfo          info          = new CurWifiInfo();
            NetworkInterfaceList interfaceList = new NetworkInterfaceList();
            NetworkInterfaceInfo interfaceInfo = interfaceList.First();

            if (!DeviceNetworkInformation.IsWiFiEnabled)
            {
                return(null);
            }

            info.ssid = interfaceInfo.InterfaceName;

            return(info);
        }
Ejemplo n.º 13
0
    private static NetworkInterface GetDotNetNetworkInterfaceByIndex(int index)
    {
#if FIRST_PASS
        return(null);
#else
        NetworkInterfaceInfo nii = GetInterfaces();
        for (int i = 0; i < nii.javaInterfaces.Length; i++)
        {
            if (nii.javaInterfaces[i].getIndex() == index)
            {
                return(nii.dotnetInterfaces[i]);
            }
        }
        throw new java.net.SocketException("interface index not found");
#endif
    }
Ejemplo n.º 14
0
        void DeviceNetworkInformation_NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(e.NotificationType);
            System.Diagnostics.Debug.WriteLine(e.NetworkInterface.InterfaceName);
            System.Diagnostics.Debug.WriteLine(e.NetworkInterface.Description);
            System.Diagnostics.Debug.WriteLine(e.NetworkInterface.InterfaceState);
            System.Diagnostics.Debug.WriteLine(e.NetworkInterface.Bandwidth);

            if (e.NotificationType == NetworkNotificationType.InterfaceConnected)
            {
                this.CurrentNetwork = e.NetworkInterface;
            }
            else if (e.NotificationType == NetworkNotificationType.InterfaceDisconnected && e.NetworkInterface == this.CurrentNetwork)
            {
                this.CurrentNetwork = null;
            }
        }
Ejemplo n.º 15
0
        public bool isNetworkConnected()
        {
            NetworkInterfaceList interfaceList = new NetworkInterfaceList();
            NetworkInterfaceInfo interfaceInfo = interfaceList.First();

            if (interfaceInfo.InterfaceState == ConnectState.Connected)
            {
                return(true);
            }
            else if (interfaceInfo.InterfaceState == ConnectState.Disconnected)
            {
                return(false);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 16
0
        public InterfaceDescriptionBlock(NetworkInterfaceInfo nic)
        {
            // Options: Interface Name (if_name)
            this.interfaceNameOption = new OptionalField(OptionTypeCode.InterfaceName, $"\\Device\\NPF_{nic.Id}");

            // Options: Interface Description (if_description)
            this.interfaceDescriptionOption = new OptionalField(OptionTypeCode.InterfaceDescription, nic.Name);

            this.TotalBlockLength =
                BlockType.Length +
                sizeof(int) +
                LinkType.Length +
                SnapLen.Length +
                this.interfaceNameOption.Length +
                this.interfaceDescriptionOption.Length +
                TsResolutionOption.Length +
                OptionalField.EndOfOptions.Length +
                sizeof(int);
        }
Ejemplo n.º 17
0
        async Task BroadcastSocket(NetworkInterfaceInfo adapter)
        {
            using (var udpClient = new UdpClient(adapter.IPAddress.AddressFamily))
            {
                var socket = udpClient.Client;

                socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(adapter.InterfaceIndex));

                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                udpClient.ExclusiveAddressUse = false;

                socket.Bind(new IPEndPoint(adapter.IPAddress, SSDP_UNICAST_PORT));

                socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(SSDP_IP, adapter.InterfaceIndex));

                var receiveTask   = ReceiveServicer(udpClient);
                var broadcastTask = BroadcastServicer(udpClient);
                await Task.WhenAll(receiveTask, broadcastTask);
            }
        }
Ejemplo n.º 18
0
        public int getNetInfo()
        {
            NetworkInterfaceList interfaceList = new NetworkInterfaceList();
            NetworkInterfaceInfo interfaceInfo = interfaceList.First();

            Debug.WriteLine("NetInfo:" + interfaceInfo.InterfaceType);
            switch (interfaceInfo.InterfaceType)
            {
            case NetworkInterfaceType.None:
                return(ENoNet);

            case NetworkInterfaceType.Wireless80211:
                return(EWifi);

            case NetworkInterfaceType.MobileBroadbandCdma:
            case NetworkInterfaceType.MobileBroadbandGsm:
                return(EMobile);

            default:
                return(EOther);
            }
        }
Ejemplo n.º 19
0
        private async static Task <JavaMapletGaussOutput> MatrixTutorResult(MapleLinearAlgebra engine, MapleMatrix matrix, string methodName)
        {
            await semaphore.WaitAsync();//Since same protocol is used for every Tutor we have to wait for other tutor's to be closed before we can recall.

            try
            {
                var engineType = typeof(MapleLinearAlgebra);
                var method     = engineType.GetMethod(methodName);                                     //reflection used since each Tutor uses same protocol, for linearalgebra, (but different call methods to maple)

                IWindow window = await(Task <IWindow>) method.Invoke(engine, new object[] { matrix }); // await engine.GaussJordanEliminationTutor(matrix);

                if (window is MSWindow)                                                                // Microsoft Windows
                {
                    // Find Loopback Pseudo interface for sniffing.
                    var nic = NetworkInterfaceInfo
                              .GetInterfaces()
                              .FirstOrDefault(c => c.Name.Contains("Loopback Pseudo"));

                    // Ensure loopback pseudo interface is found before we start trying to sniff.
                    if (nic != default(NetworkInterfaceInfo))
                    {
                        PcapNgFileOutput output;
                        SocketSniffer    sniffer;

                        StartSniffing(nic, out output, out sniffer);
                        await InteractWithDefaultTutor((MSWindow)window, sniffer);

                        StopSniffing(output, sniffer);
                        return(InterpretMatrixSniffedData());
                    }
                }
            } finally
            {
                semaphore.Release();
            }

            return(null);
        }
Ejemplo n.º 20
0
        private async void LoadNetworkInterfaces()
        {
            IsNetworkInterfaceLoading = true;

            NetworkInterfaces = await Models.Network.NetworkInterface.GetNetworkInterfacesAsync();

            // Get the last selected interface, if it is still available on this machine...
            if (NetworkInterfaces.Count > 0)
            {
                NetworkInterfaceInfo info = NetworkInterfaces.Where(s => s.Id == SettingsManager.Current.NetworkInterface_SelectedInterfaceId).FirstOrDefault();

                if (info != null)
                {
                    SelectedNetworkInterface = info;
                }
                else
                {
                    SelectedNetworkInterface = NetworkInterfaces[0];
                }
            }

            IsNetworkInterfaceLoading = false;
        }
Ejemplo n.º 21
0
        private void OnShareButtonClick(object sender, MouseEventArgs e)
        {
            if (SSIDText.Text.Length < 5)
            {
                MessageBox.Show("SSID Name must be at least 5 characters long."
                                , Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (KeyText.Text.Length < 6)
            {
                MessageBox.Show("Password must be at least 6 characters long."
                                , Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (NetIList.SelectedIndex < 0)
            {
                MessageBox.Show("Network interface not selected.\n\n" +
                                "Please select a network interface that you want to share its internet connection."
                                , Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                ((Button)sender).Enabled = false;
                NetworkInterfaceInfo NetITFInfo = NetInterfaceList[NetIList.SelectedIndex];
                Settings.Save(SSIDText.Text, KeyText.Text);

                new Thread(() =>
                {
                    Settings.Read();
                    StartHostedNetwork(Settings.SSID, Settings.Key, NetITFInfo.InterfaceGuid);
                    this?.Invoke(new Action(() => ((Button)sender).Enabled = true));
                })
                {
                    IsBackground = false,
                    Priority     = ThreadPriority.AboveNormal
                }.Start();
            }
        }
Ejemplo n.º 22
0
        public SocketSniffer(NetworkInterfaceInfo nic, ILogger logger, PacketDataAnalyzer analyzer)
        {
            _logger        = logger;
            _outputQueue   = new BlockingCollection <TimestampedData>();
            _analyzer      = analyzer;
            _bufferManager = new BufferManager(BUFFER_SIZE, MAX_RECEIVE);
            _receivePool   = new ConcurrentStack <SocketAsyncEventArgs>();

            // IPv4
            this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            this._socket.Bind(new IPEndPoint(nic.IPAddress, 0));
            this._socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

            // Enter promiscuous mode
            try
            {
                this._socket.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), new byte[4]);
            }
            catch (Exception ex)
            {
                _logger.Log(Severity.Debug, $"Unable to enter promiscuous mode: {ex}");
                throw;
            }
        }
Ejemplo n.º 23
0
        private static bool IsSlowNetwork(NetworkInterfaceInfo netInfo)
        {
            switch (netInfo.InterfaceType)
            {
            case NetworkInterfaceType.MobileBroadbandCdma:
            case NetworkInterfaceType.MobileBroadbandGsm:
                return(true);

            case NetworkInterfaceType.Ethernet:
            case NetworkInterfaceType.Wireless80211:
                return(false);

            default:
                switch (netInfo.InterfaceSubtype)
                {
                case NetworkInterfaceSubType.WiFi:
                case NetworkInterfaceSubType.Desktop_PassThru:
                    return(false);

                default:
                    return(true);
                }
            }
        }
Ejemplo n.º 24
0
        private async static Task <JavaMapletGaussOutput> TutorResult(MapleLinearAlgebra engine, MapleMatrix matrix, string methodName)
        {
            List <string> operations  = new List <string>();
            var           gaussOutput = new JavaMapletGaussOutput();

            await semaphoreSlim.WaitAsync();//Since same protocol is used for every Tutor we have to wait for other tutor's to be closed before we can recall.

            try
            {
                var engineType = typeof(MapleLinearAlgebra);
                var method     = engineType.GetMethod(methodName);                                     //reflection used since each Tutor uses same protocol, for linearalgebra, (but different call methods to maple)

                IWindow window = await(Task <IWindow>) method.Invoke(engine, new object[] { matrix }); // await engine.GaussJordanEliminationTutor(matrix);
                if (window is MSWindow)                                                                // Microsoft Windows
                {
                    // Find interfaces for sniffing.
                    var nics = NetworkInterfaceInfo.GetInterfaces();
                    var nic  = nics.FirstOrDefault(c => c.Name.Contains("Loopback Pseudo"));

                    // Ensure loopback pseudo interface is found...
                    if (nic != default(NetworkInterfaceInfo))
                    {
                        #region Start Sniffing
                        var appOptions = new AppOptions();
                        appOptions.Parse(new string[] { "" });
                        var filters = appOptions.BuildFilters();
                        var output  = new PcapNgFileOutput(nic, appOptions.Filename);
                        var sniffer = new SocketSniffer(nic, filters, output);
                        sniffer.Start();
                        #endregion

                        #region MSWIN
                        var mswin = (MSWindow)window;
                        mswin.WindowPos(0, 0, 400, 800);

                        for (int i = 0; i < 4; i++)
                        {
                            mswin.SendKeyStroke(System.Windows.Forms.Keys.Tab);
                            await Task.Delay(60);
                        }

                        mswin.SendKeyStroke(System.Windows.Forms.Keys.Enter);
                        mswin.Hide();
                        long LastPackageCount = 0;
                        int  WaitTries        = 0;
                        while (true) // wait for program to stop sending packages to intercept.
                        {
                            await Task.Delay(400);

                            LastPackageCount = sniffer.PacketsCaptured;
                            if (LastPackageCount > 0 && LastPackageCount == sniffer.PacketsCaptured)
                            {
                                WaitTries++;
                            }
                            if (WaitTries > 4)
                            {
                                break;
                            }
                        }
                        mswin.Close();
                        #endregion

                        #region Interpret Sniffed Data
                        sniffer.Stop();
                        output.Dispose();

                        using (var reader = new StreamReader("snifter.pcapng"))
                        {
                            var content = reader.ReadToEnd();
                            var regex   = new Regex(@"\<application_communications.*?\<content\>Applied operation\:\ (.*?)\<\/content\>", RegexOptions.Singleline);
                            var match   = regex.Match(content);

                            while (match.Success)
                            {
                                var operation = match.Groups[1].Value.Trim();//initial space
                                operations.Add(operation);
                                match = match.NextMatch();
                            }

                            var mapleMatrixRegex = new Regex(@"\<content\>(\&lt\;.*?)\<", RegexOptions.Singleline);
                            var mapleMatrixMatch = mapleMatrixRegex.Match(content);

                            var lastMatchStr = "";
                            while (mapleMatrixMatch.Success)
                            {
                                lastMatchStr     = mapleMatrixMatch.Groups[1].Value;
                                mapleMatrixMatch = mapleMatrixMatch.NextMatch();
                            }

                            StringBuilder builder = new StringBuilder(lastMatchStr);
                            gaussOutput.Operations = operations.ToArray();

                            int ra_index = 0;
                            int index    = 0;
                            var search   = "mtext&gt;&amp;NewLine;";
                            while ((ra_index = builder.ToString().IndexOf(search, ra_index)) != -1)
                            {
                                ra_index += search.Length;
                                if (index >= operations.Count)
                                {
                                    break;
                                }
                                builder.Insert(ra_index, $" {gaussOutput.OperationsDa[index++]} &amp;NewLine;&amp;NewLine;&amp;NewLine;");
                            }


                            gaussOutput.MathML = HttpUtility.HtmlDecode(builder.ToString());
                        }
                        #endregion
                    }
                }
            } finally
            {
                semaphoreSlim.Release();
            }

            return(gaussOutput);
        }
Ejemplo n.º 25
0
        public static void GetNetName()
        {
            DeviceNetworkInformation.ResolveHostNameAsync(
                new DnsEndPoint("www.microsoft.com", 80),
                new NameResolutionCallback(handle =>
            {
                string Name               = "";
                string NetName            = "";
                NetworkInterfaceInfo info = handle.NetworkInterface;
                if (info != null)
                {
                    Name = info.InterfaceName + " " + info.Description + " ";

                    switch (info.InterfaceType)
                    {
                    case NetworkInterfaceType.Ethernet:
                        NetName = "Ethernet";
                        break;

                    case NetworkInterfaceType.MobileBroadbandCdma:
                    case NetworkInterfaceType.MobileBroadbandGsm:
                        switch (info.InterfaceSubtype)
                        {
                        case NetworkInterfaceSubType.Cellular_3G:
                            //NetName = "Cellular_3G + 3G";
                            NetName = "3G";
                            break;

                        case NetworkInterfaceSubType.Cellular_EVDO:
                            //NetName = "Cellular_EVDO + 3G";
                            NetName = "3G";
                            break;

                        case NetworkInterfaceSubType.Cellular_EVDV:
                            //NetName = "Cellular_EVDV + 3G";
                            NetName = "3G";
                            break;

                        case NetworkInterfaceSubType.Cellular_HSPA:
                            NetName = "3G";
                            //NetName = "Cellular_HSPA + 3G";
                            break;

                        case NetworkInterfaceSubType.Cellular_GPRS:
                            //NetName = "Cellular_GPRS + 2G";
                            NetName = "2G";
                            break;

                        case NetworkInterfaceSubType.Cellular_EDGE:
                            NetName = "2G";
                            // NetName = "Cellular_EDGE + 2G";
                            break;

                        case NetworkInterfaceSubType.Cellular_1XRTT:
                            //NetName = "Cellular_1XRTT + 2G";
                            NetName = "2G";
                            break;

                        default:
                            NetName = "None";
                            break;
                        }
                        break;

                    case NetworkInterfaceType.Wireless80211:
                        NetName = "WiFi";
                        break;

                    default:
                        NetName = "None";
                        break;
                    }
                }
                else
                {
                    NetName = "None";
                }

                CommonData.NetworkStatus = NetName;
                string tip = "";
                if (NetName == "None")
                {
                    tip = AppResources.NoneNetwork;
                }
                else
                {
                    tip = AppResources.ShowNetwork.Replace("#name#", NetName);
                }

                if (NetName != "WiFi")
                {
                    App.DownVideoModel.StopGetVideoData();
                }
                else
                {
                    App.DownVideoModel.CheckLocalData();
                }

                ShowToast(tip);
            }), null);
        }
 public NetworkInterfaceModel(NetworkInterfaceInfo info)
 {
     Data = info;
 }
Ejemplo n.º 27
0
 private static bool IsSlowNetwork(NetworkInterfaceInfo netInfo)
 {
     switch (netInfo.InterfaceType)
     {
         case NetworkInterfaceType.MobileBroadbandCdma:
         case NetworkInterfaceType.MobileBroadbandGsm:
             return true;
         case NetworkInterfaceType.Ethernet:
         case NetworkInterfaceType.Wireless80211:
             return false;
         default:
             switch (netInfo.InterfaceSubtype)
             {
                 case NetworkInterfaceSubType.WiFi:
                 case NetworkInterfaceSubType.Desktop_PassThru:
                     return false;
                 default:
                     return true;
             }
     }
 }
Ejemplo n.º 28
0
        public static List <NetworkInterfaceInfo> GetLocalNetworkInterfaces(
            SubnetClass subnetClasses = SubnetClass.C,
            bool flushCache           = false)
        {
            if (flushCache)
            {
                localNetworkInterfaces = null;
            }

            if (localNetworkInterfaces != null)
            {
                return(localNetworkInterfaces);
            }

            List <NetworkInterfaceInfo> workingInterfaces = new List <NetworkInterfaceInfo>();

            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface networkInterface in networkInterfaces)
            {
                if ((networkInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
                    (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Tunnel) ||
                    (networkInterface.OperationalStatus != OperationalStatus.Up))
                {
                    continue;
                }

                IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                foreach (UnicastIPAddressInformation ipInformation in ipProperties.UnicastAddresses)
                {
                    IPAddress ipv4Mask = null;

                    if (OSVersionPlatform.GetGenericPlatform() == PlatformID.Unix)
                    {
                        //Mono does not implement IPv4Mask
                        //see https://bugzilla.xamarin.com/show_bug.cgi?id=2033
                        string mask = IPInfoTools.GetIPv4Mask(networkInterface.Name);
                        if (mask == null || IPAddress.TryParse(mask, out ipv4Mask) == false)
                        {
                            ipv4Mask = IPAddress.Parse("255.255.255.0"); // default to this
                        }
                    }
                    else
                    {
                        ipv4Mask = ipInformation.IPv4Mask;
                    }

                    SubnetClass interfaceClass = ipv4Mask.GetSubnetClass();

                    //optionally scan class A & B subnets
                    if (!((subnetClasses & interfaceClass) == interfaceClass))
                    {
                        continue;
                    }

                    IPAddress ipAddress = ipInformation.Address;

                    if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                    {
                        NetworkInterfaceInfo interfaceInfo = new NetworkInterfaceInfo();

                        interfaceInfo.Host      = ipAddress;
                        interfaceInfo.Netmask   = ipv4Mask;
                        interfaceInfo.Broadcast = GetBroadcastAddress(interfaceInfo.Host, interfaceInfo.Netmask);

                        //deprecations are known - we only support IPv4 scanning with this code
                        //see above check for AddressFamily.InterNetwork
                        long host       = (long)(uint)IPAddress.NetworkToHostOrder((int)interfaceInfo.Host.Address);
                        long netmask    = (long)(uint)IPAddress.NetworkToHostOrder((int)interfaceInfo.Netmask.Address);
                        long broadcast  = (long)(uint)IPAddress.NetworkToHostOrder((int)interfaceInfo.Broadcast.Address);
                        long network    = host & netmask;
                        long rangeStart = network + 1;
                        long rangeEnd   = broadcast - 1;

                        //e.g. if host == broadcast, netmask == 255.255.255.255
                        if (rangeEnd < rangeStart)
                        {
                            long swap = rangeEnd;
                            rangeEnd   = rangeStart;
                            rangeStart = swap;
                        }

                        interfaceInfo.RangeStart = new IPAddress((long)(uint)IPAddress.HostToNetworkOrder((int)rangeStart));
                        interfaceInfo.RangeEnd   = new IPAddress((long)(uint)IPAddress.HostToNetworkOrder((int)rangeEnd));

                        workingInterfaces.Add(interfaceInfo);
                    }
                }
            }

            //cache the results
            localNetworkInterfaces = workingInterfaces;

            return(localNetworkInterfaces);
        }
Ejemplo n.º 29
0
 public InterfaceDescriptionBlock(NetworkInterfaceInfo nic)
 {
     this.nic = nic;
 }
Ejemplo n.º 30
0
        public static IObservable <NameResolutionResult> ResolveHostName(DnsEndPoint endPoint, NetworkInterfaceInfo networkInterface)
        {
            Contract.Requires(endPoint != null);
            Contract.Requires(networkInterface != null);
            Contract.Ensures(Contract.Result <IObservable <NameResolutionResult> >() != null);

            var subject = new AsyncSubject <NameResolutionResult>();

            try
            {
                DeviceNetworkInformation.ResolveHostNameAsync(
                    endPoint,
                    networkInterface,
                    result =>
                {
                    var s = (AsyncSubject <NameResolutionResult>)result.AsyncState;

                    s.OnNext(result);
                    s.OnCompleted();
                },
                    subject);
            }
            catch (Exception ex)
            {
                subject.OnError(ex);
            }

            return(subject.AsObservable());
        }
Ejemplo n.º 31
0
        private static void NetworkInformationCallback(NetworkInterfaceInfo netInfo)
        {
            // set encoding behavior based on speed of network: wifi networks don't need encoding,
            // but cellular networks do
            string encString;
            if (IsSlowNetwork(netInfo))
            {
                encode = true;
                encString = "application/speex";
            }
            else
            {
                encode = false;
                encString = "application/pcm";
            }

            // initialize the encoding
            encoding = String.Format("{0}-{1}-{2}-{3}",
                encString,
                mic.SampleRate,
                "16",  // 16 bits per sample
                ((int)AudioChannels.Mono).ToString());  // 1 audio channel (mono)

            // Trace the operation
            TraceHelper.AddMessage("POST: " + encoding);

            // send the HTTP POST to initialize the speech operation
            // upon completion it will invoke the StartMic delegate to start the microphone
            NetworkHelper.SendPost(
                user,
                "Zaplify-Speech-Encoding: " + encoding,
                new StartMicDelegate(StartMic),
                new NetworkDelegate(NetworkCallback));
        }
Ejemplo n.º 32
0
        void DeviceNetworkInformation_NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(e.NotificationType);
            System.Diagnostics.Debug.WriteLine(e.NetworkInterface.InterfaceName);
            System.Diagnostics.Debug.WriteLine(e.NetworkInterface.Description);
            System.Diagnostics.Debug.WriteLine(e.NetworkInterface.InterfaceState);
            System.Diagnostics.Debug.WriteLine(e.NetworkInterface.Bandwidth);

            if (e.NotificationType == NetworkNotificationType.InterfaceConnected)
            {
                this.CurrentNetwork = e.NetworkInterface;
            }
            else if (e.NotificationType == NetworkNotificationType.InterfaceDisconnected && e.NetworkInterface == this.CurrentNetwork)
            {
                this.CurrentNetwork = null;
            }
        }
Ejemplo n.º 33
0
        public static List<NetworkInterfaceInfo> GetLocalNetworkInterfaces(
            SubnetClass subnetClasses = SubnetClass.C, 
            bool flushCache = false)
        {
            if (flushCache)
                localNetworkInterfaces = null;

            if (localNetworkInterfaces != null)
                return localNetworkInterfaces;

            List<NetworkInterfaceInfo> workingInterfaces = new List<NetworkInterfaceInfo>();

            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface networkInterface in networkInterfaces)
            {
                if ((networkInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
                    (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Tunnel) ||
                    (networkInterface.OperationalStatus != OperationalStatus.Up))
                    continue;

                IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                foreach (UnicastIPAddressInformation ipInformation in ipProperties.UnicastAddresses)
                {
                    IPAddress ipv4Mask = null;

                    if (OSVersionPlatform.GetGenericPlatform() == PlatformID.Unix)
                    {
                        //Mono does not implement IPv4Mask
                        //see https://bugzilla.xamarin.com/show_bug.cgi?id=2033
                        string mask = IPInfoTools.GetIPv4Mask(networkInterface.Name);
                        if (mask == null || IPAddress.TryParse(mask, out ipv4Mask) == false)
                            ipv4Mask = IPAddress.Parse("255.255.255.0"); // default to this
                    }
                    else
                        ipv4Mask = ipInformation.IPv4Mask;

                    SubnetClass interfaceClass = ipv4Mask.GetSubnetClass();
                                        
                    //optionally scan class A & B subnets
                    if (!((subnetClasses & interfaceClass) == interfaceClass))
                        continue;

                    IPAddress ipAddress = ipInformation.Address;

                    if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                    {
                        NetworkInterfaceInfo interfaceInfo = new NetworkInterfaceInfo();

                        interfaceInfo.Host = ipAddress;
                        interfaceInfo.Netmask = ipv4Mask;
                        interfaceInfo.Broadcast = GetBroadcastAddress(interfaceInfo.Host, interfaceInfo.Netmask);

                        //deprecations are known - we only support IPv4 scanning with this code
                        //see above check for AddressFamily.InterNetwork
                        long host = (long)(uint)IPAddress.NetworkToHostOrder((int)interfaceInfo.Host.Address);
                        long netmask = (long)(uint)IPAddress.NetworkToHostOrder((int)interfaceInfo.Netmask.Address);
                        long broadcast = (long)(uint)IPAddress.NetworkToHostOrder((int)interfaceInfo.Broadcast.Address);
                        long network = host & netmask;
                        long rangeStart = network + 1;
                        long rangeEnd = broadcast - 1;

                        //e.g. if host == broadcast, netmask == 255.255.255.255
                        if (rangeEnd < rangeStart)
                        {
                            long swap = rangeEnd;
                            rangeEnd = rangeStart;
                            rangeStart = swap;
                        }

                        interfaceInfo.RangeStart = new IPAddress((long)(uint)IPAddress.HostToNetworkOrder((int)rangeStart));
                        interfaceInfo.RangeEnd = new IPAddress((long)(uint)IPAddress.HostToNetworkOrder((int)rangeEnd));

                        workingInterfaces.Add(interfaceInfo);
                    }
                }
            }

            //cache the results
            localNetworkInterfaces = workingInterfaces;

            return localNetworkInterfaces;
        }
Ejemplo n.º 34
0
    private static NetworkInterfaceInfo GetInterfaces()
    {
        // Since many of the methods in java.net.NetworkInterface end up calling this method and the underlying stuff this is
        // based on isn't very quick either, we cache the array for a couple of seconds.
        if (cache != null && DateTime.UtcNow - cachedSince < new TimeSpan(0, 0, 5))
        {
            return(cache);
        }
        NetworkInterface[] ifaces = NetworkInterface.GetAllNetworkInterfaces();
        // on Mono (on Windows) we need to filter out the network interfaces that don't have any IP properties
        ifaces = Array.FindAll(ifaces, IsValid);
        Array.Sort(ifaces, Compare);
        java.net.NetworkInterface[] ret = new java.net.NetworkInterface[ifaces.Length];
        int eth  = 0;
        int tr   = 0;
        int fddi = 0;
        int lo   = 0;
        int ppp  = 0;
        int sl   = 0;
        int net  = 0;

        for (int i = 0; i < ifaces.Length; i++)
        {
            string name;
            switch (ifaces[i].NetworkInterfaceType)
            {
            case NetworkInterfaceType.Ethernet:
                name = "eth" + eth++;
                break;

            case NetworkInterfaceType.TokenRing:
                name = "tr" + tr++;
                break;

            case NetworkInterfaceType.Fddi:
                name = "fddi" + fddi++;
                break;

            case NetworkInterfaceType.Loopback:
                if (lo > 0)
                {
                    continue;
                }
                name = "lo";
                lo++;
                break;

            case NetworkInterfaceType.Ppp:
                name = "ppp" + ppp++;
                break;

            case NetworkInterfaceType.Slip:
                name = "sl" + sl++;
                break;

            default:
                name = "net" + net++;
                break;
            }
            java.net.NetworkInterface netif = new java.net.NetworkInterface();
            ret[i] = netif;
            netif._set1(name, ifaces[i].Description, GetIndex(ifaces[i]));
            UnicastIPAddressInformationCollection uipaic    = ifaces[i].GetIPProperties().UnicastAddresses;
            List <java.net.InetAddress>           addresses = new List <java.net.InetAddress>();
            List <java.net.InterfaceAddress>      bindings  = new List <java.net.InterfaceAddress>();
            for (int j = 0; j < uipaic.Count; j++)
            {
                IPAddress addr = uipaic[j].Address;
                if (addr.AddressFamily == AddressFamily.InterNetwork)
                {
                    java.net.Inet4Address     address = new java.net.Inet4Address(null, addr.GetAddressBytes());
                    java.net.InterfaceAddress binding = new java.net.InterfaceAddress();
                    short mask = 32;
                    java.net.Inet4Address broadcast = null;
                    IPAddress             v4mask;
                    try
                    {
                        v4mask = uipaic[j].IPv4Mask;
                    }
                    catch (NotImplementedException)
                    {
                        // Mono (as of 2.6.7) doesn't implement the IPv4Mask property
                        v4mask = null;
                    }
                    if (v4mask != null && !v4mask.Equals(IPAddress.Any))
                    {
                        broadcast = new java.net.Inet4Address(null, -1);
                        mask      = 0;
                        foreach (byte b in v4mask.GetAddressBytes())
                        {
                            mask += (short)java.lang.Integer.bitCount(b);
                        }
                    }
                    else if (address.isLoopbackAddress())
                    {
                        mask      = 8;
                        broadcast = new java.net.Inet4Address(null, 0xffffff);
                    }
                    binding._set(address, broadcast, mask);
                    addresses.Add(address);
                    bindings.Add(binding);
                }
                else if (Java_java_net_InetAddressImplFactory.isIPv6Supported())
                {
                    int scope = 0;
                    if (addr.IsIPv6LinkLocal || addr.IsIPv6SiteLocal)
                    {
                        scope = (int)addr.ScopeId;
                    }
                    java.net.Inet6Address ia6 = new java.net.Inet6Address();
                    ia6._holder().ipaddress   = addr.GetAddressBytes();
                    if (scope != 0)
                    {
                        ia6._holder().scope_id         = scope;
                        ia6._holder().scope_id_set     = true;
                        ia6._holder().scope_ifname     = netif;
                        ia6._holder().scope_ifname_set = true;
                    }
                    java.net.InterfaceAddress binding = new java.net.InterfaceAddress();
                    // TODO where do we get the IPv6 subnet prefix length?
                    short mask = 128;
                    binding._set(ia6, null, mask);
                    addresses.Add(ia6);
                    bindings.Add(binding);
                }
            }
            netif._set2(addresses.ToArray(), bindings.ToArray(), new java.net.NetworkInterface[0]);
        }
        NetworkInterfaceInfo nii = new NetworkInterfaceInfo();

        nii.dotnetInterfaces = ifaces;
        nii.javaInterfaces   = ret;
        cache       = nii;
        cachedSince = DateTime.UtcNow;
        return(nii);
    }
Ejemplo n.º 35
0
    public static IObservable<NameResolutionResult> ResolveHostName(DnsEndPoint endPoint, NetworkInterfaceInfo networkInterface)
    {
      Contract.Requires(endPoint != null);
      Contract.Requires(networkInterface != null);
      Contract.Ensures(Contract.Result<IObservable<NameResolutionResult>>() != null);

      var subject = new AsyncSubject<NameResolutionResult>();

      try
      {
        DeviceNetworkInformation.ResolveHostNameAsync(
          endPoint,
          networkInterface,
          result =>
          {
            var s = (AsyncSubject<NameResolutionResult>) result.AsyncState;

            s.OnNext(result);
            s.OnCompleted();
          },
          subject);
      }
      catch (Exception ex)
      {
        subject.OnError(ex);
      }

      return subject.AsObservable();
    }
Ejemplo n.º 36
0
 private static NetworkInterfaceInfo GetInterfaces()
 {
     // Since many of the methods in java.net.NetworkInterface end up calling this method and the underlying stuff this is
     // based on isn't very quick either, we cache the array for a couple of seconds.
     if (cache != null && DateTime.UtcNow - cachedSince < new TimeSpan(0, 0, 5))
     {
         return cache;
     }
     NetworkInterface[] ifaces = NetworkInterface.GetAllNetworkInterfaces();
     // on Mono (on Windows) we need to filter out the network interfaces that don't have any IP properties
     ifaces = Array.FindAll(ifaces, IsValid);
     Array.Sort(ifaces, Compare);
     java.net.NetworkInterface[] ret = new java.net.NetworkInterface[ifaces.Length];
     int eth = 0;
     int tr = 0;
     int fddi = 0;
     int lo = 0;
     int ppp = 0;
     int sl = 0;
     int net = 0;
     for (int i = 0; i < ifaces.Length; i++)
     {
         string name;
         switch (ifaces[i].NetworkInterfaceType)
         {
             case NetworkInterfaceType.Ethernet:
                 name = "eth" + eth++;
                 break;
             case NetworkInterfaceType.TokenRing:
                 name = "tr" + tr++;
                 break;
             case NetworkInterfaceType.Fddi:
                 name = "fddi" + fddi++;
                 break;
             case NetworkInterfaceType.Loopback:
                 if (lo > 0)
                 {
                     continue;
                 }
                 name = "lo";
                 lo++;
                 break;
             case NetworkInterfaceType.Ppp:
                 name = "ppp" + ppp++;
                 break;
             case NetworkInterfaceType.Slip:
                 name = "sl" + sl++;
                 break;
             default:
                 name = "net" + net++;
                 break;
         }
         java.net.NetworkInterface netif = new java.net.NetworkInterface();
         ret[i] = netif;
         netif._set1(name, ifaces[i].Description, GetIndex(ifaces[i]));
         UnicastIPAddressInformationCollection uipaic = ifaces[i].GetIPProperties().UnicastAddresses;
         List<java.net.InetAddress> addresses = new List<java.net.InetAddress>();
         List<java.net.InterfaceAddress> bindings = new List<java.net.InterfaceAddress>();
         for (int j = 0; j < uipaic.Count; j++)
         {
             IPAddress addr = uipaic[j].Address;
             if (addr.AddressFamily == AddressFamily.InterNetwork)
             {
                 java.net.Inet4Address address = new java.net.Inet4Address(null, addr.GetAddressBytes());
                 java.net.InterfaceAddress binding = new java.net.InterfaceAddress();
                 short mask = 32;
                 java.net.Inet4Address broadcast = null;
                 IPAddress v4mask;
                 try
                 {
                     v4mask = uipaic[j].IPv4Mask;
                 }
                 catch (NotImplementedException)
                 {
                     // Mono (as of 2.6.7) doesn't implement the IPv4Mask property
                     v4mask = null;
                 }
                 if (v4mask != null && !v4mask.Equals(IPAddress.Any))
                 {
                     broadcast = new java.net.Inet4Address(null, -1);
                     mask = 0;
                     foreach (byte b in v4mask.GetAddressBytes())
                     {
                         mask += (short)java.lang.Integer.bitCount(b);
                     }
                 }
                 else if (address.isLoopbackAddress())
                 {
                     mask = 8;
                     broadcast = new java.net.Inet4Address(null, 0xffffff);
                 }
                 binding._set(address, broadcast, mask);
                 addresses.Add(address);
                 bindings.Add(binding);
             }
             else if (Java_java_net_InetAddressImplFactory.isIPv6Supported())
             {
                 int scope = 0;
                 if (addr.IsIPv6LinkLocal || addr.IsIPv6SiteLocal)
                 {
                     scope = (int)addr.ScopeId;
                 }
                 java.net.Inet6Address ia6 = new java.net.Inet6Address();
                 ia6._holder().ipaddress = addr.GetAddressBytes();
                 if (scope != 0)
                 {
                     ia6._holder().scope_id = scope;
                     ia6._holder().scope_id_set = true;
                     ia6._holder().scope_ifname = netif;
                     ia6._holder().scope_ifname_set = true;
                 }
                 java.net.InterfaceAddress binding = new java.net.InterfaceAddress();
                 // TODO where do we get the IPv6 subnet prefix length?
                 short mask = 128;
                 binding._set(ia6, null, mask);
                 addresses.Add(ia6);
                 bindings.Add(binding);
             }
         }
         netif._set2(addresses.ToArray(), bindings.ToArray(), new java.net.NetworkInterface[0]);
     }
     NetworkInterfaceInfo nii = new NetworkInterfaceInfo();
     nii.dotnetInterfaces = ifaces;
     nii.javaInterfaces = ret;
     cache = nii;
     cachedSince = DateTime.UtcNow;
     return nii;
 }
Ejemplo n.º 37
0
        private async Task<Host> GetEc2Instance(string id)
        {
            var instance = await ec2.DescribeInstanceAsync(id).ConfigureAwait(false);

            var host = new Host {
                Type = HostType.VirtualInstance,
                RefId = instance.InstanceId,
                Addresses = new List<IPAddress>() {
                    IPAddress.Parse(instance.IpAddress),
                    IPAddress.Parse(instance.PrivateIpAddress)
                },
                Details = new JsonObject {
                    { "availabilityZone", instance.Placement.AvailabilityZone },
                    { "instanceType", instance.InstanceType },
                    { "hypervisor", instance.Hypervisor },
                    { "vpcId", instance.VpcId }
                },
                Provider = PlatformProviderId.Amazon,
                Status = GetStatus(instance.InstanceState),
                Modified = DateTime.UtcNow,
                Created = instance.LaunchTime
            };

            // "imageId": "ami-1647537c",

            if (instance.ImageId != null)
            {
                // Images may be shared
                var image = (await db.Images.QueryFirstOrDefaultAsync(Eq("refId", instance.ImageId)));

                if (image == null)
                {
                    image = new Image
                    {
                        RefId = instance.ImageId,
                        // Architecture = instance.Architecture,
                        Created = DateTime.UtcNow
                    };

                    await db.Images.InsertAsync(image).ConfigureAwait(false);

                    host.ImageId = image.Id;
                }
            }

            await db.Hosts.InsertAsync(host);

            foreach (var v in instance.BlockDeviceMappings)
            {
                if (v.Ebs != null)
                {
                    var vv = await ec2.DescribeVolumeAsync(v.Ebs.VolumeId).ConfigureAwait(false);

                    var vol = new VolumeInfo {
                        RefId    = v.Ebs.VolumeId,
                        Provider = PlatformProviderId.Amazon,
                        Status   = VolumeStatus.Online,
                        Size     = (long)vv.Size * 1073741824,
                        HostId   = host.Id,
                        Created  = vv.CreateTime
                    };

                    await db.Volumes.InsertAsync(vol).ConfigureAwait(false);
                }
            }

            foreach (var ni in instance.NetworkInterfaces)
            {
                var networkInterface = new NetworkInterfaceInfo {
                    MacAddress = ni.MacAddress,
                    Provider = PlatformProviderId.Amazon,
                    RefId = ni.NetworkInterfaceId,
                    HostId = host.Id,
                    Details = new JsonObject {
                        { "subnetId", ni.SubnetId },
                        { "vpcId", ni.VpcId }
                    },
                    Created = DateTime.UtcNow
                };

                /*
                if (ni.Groups != null)
                {
                    var list = new XList<string>(ni.Groups.Select(ni );

                    foreach (var group in ni.Groups)
                    {
                    }
                }
                */

                // ? IP addresses
                // ? Security groups

                await db.NetworkInterfaces.InsertAsync(networkInterface).ConfigureAwait(false);
            }

            return host;
        }
Ejemplo n.º 38
0
 public InterfaceDescriptionBlock(NetworkInterfaceInfo nic)
 {
     this.nic = nic;
 }
Ejemplo n.º 39
0
        private static void InvokeNetworkRequest(Delegate del, Delegate netOpInProgressDel)
        {
            // this code is non-reentrant
            if (isRequestInProgress == true)
            {
                return;
            }

            // set the request in progress flag
            isRequestInProgress = true;

            // signal that a network operation is starting
            netOpInProgressDel.DynamicInvoke(true, OperationStatus.Started);

            // get a Uri for the service - this will be used to decode the host / port
            Uri uri = new Uri(SpeechUrl);

            // create the socket
            if (socket == null)
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if (uri.Host == "localhost")
                {
                    endPoint = new IPEndPoint(IPAddress.Loopback, uri.Port);
                }
                else
                {
                    endPoint = new DnsEndPoint(uri.Host, uri.Port, AddressFamily.InterNetwork);
                }
            }

            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();

            socketEventArg.RemoteEndPoint = endPoint;

            // set the connect completion delegate
            socketEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
            {
                if (e.SocketError != SocketError.Success)
                {
                    // signal that a network operation is done and unsuccessful
                    netOpInProgressDel.DynamicInvoke(false, OperationStatus.Failed);

                    // clean up the socket
                    CleanupSocket();

                    return;
                }

                // get the current network interface info
                NetworkInterfaceInfo netInterfaceInfo = socket.GetCurrentNetworkInterface();

                // invoke the completion delegate with the network type info
                del.DynamicInvoke(netInterfaceInfo);
            });

            // if the socket isn't connected, connect now
            if (socket.Connected == false)
            {
                // connect to the service
                try
                {
                    bool ret = socket.ConnectAsync(socketEventArg);
                    if (ret == false)
                    {
                        // signal that a network operation is done and unsuccessful
                        netOpInProgressDel.DynamicInvoke(false, OperationStatus.Failed);

                        // clean up the socket
                        CleanupSocket();
                    }
                }
                catch (Exception ex)
                {
                    // trace network error
                    TraceHelper.AddMessage("InvokeNetworkRequest: ex: " + ex.Message);

                    // signal that a network operation is done and unsuccessful
                    netOpInProgressDel.DynamicInvoke(false, OperationStatus.Failed);

                    // clean up the socket
                    CleanupSocket();
                }
            }
            else
            {
                // socket already connected

                // get the current network interface info
                NetworkInterfaceInfo netInterfaceInfo = socket.GetCurrentNetworkInterface();

                // invoke the completion delegate with the network type info
                del.DynamicInvoke(netInterfaceInfo);
            }
        }