/// <summary> /// Search devices on the local network. /// </summary> /// <param name="timeoutMiliseconds">Timeout to search devices.</param> /// <param name="stopOnFirstDevice">Indicates wheter the Discovery Service must stop when find the first device.</param> /// <returns>All found devices.</returns> public static async Task <IEnumerable <IDeviceInfo> > GetAllDevices(bool stopOnFirstDevice = false, uint timeoutMiliseconds = 3000) { if (timeoutMiliseconds == 0) { throw new InvalidOperationException("Timeout must be greater than zero."); } var devices = new List <IDeviceInfo>(); var timeoutCancellationTokenSource = new CancellationTokenSource(); using (var socket = new DatagramSocket()) { socket.MessageReceived += async(sender, args) => { var reader = args.GetDataReader(); var deviceLocationUri = GetDeviceLocation(reader.ReadString(reader.UnconsumedBufferLength)); var deviceInfo = await GetDeviceInfo(deviceLocationUri); #if DEBUG Debug.WriteLine(string.Format("DEVICE FOUND: Name = {0}, Manufacturer = {1}, Model = {2}, Address = {3}", deviceInfo.FriendlyName, deviceInfo.Manufacturer, deviceInfo.Model, deviceInfo.UrlBase)); #endif devices.Add(deviceInfo); if (stopOnFirstDevice) { timeoutCancellationTokenSource.Cancel(); } }; await socket.BindEndpointAsync(null, ""); socket.JoinMulticastGroup(DialConstants.MulticastHost); var writer = new DataWriter(await socket.GetOutputStreamAsync(DialConstants.MulticastHost, DialConstants.UdpPort)); writer.WriteString(string.Format(DialConstants.MSearchMessage, DialConstants.MulticastHost, DialConstants.UdpPort)); await writer.StoreAsync(); try { await Task.Delay((int)timeoutMiliseconds, timeoutCancellationTokenSource.Token); } catch {} } return(devices); }
/// <summary> /// Opens the server at the given port and starts the listener thread. /// </summary> /// #if NETFX_CORE public async void Connect() { Debug.Log("Waiting for a connection... " + _localPort.ToString()); socket = new DatagramSocket(); socket.Control.QualityOfService = SocketQualityOfService.LowLatency; socket.Control.DontFragment = true; socket.Control.InboundBufferSizeInBytes = 10000; socket.MessageReceived += Socket_MessageReceived; try { await socket.BindEndpointAsync(null, _localPort.ToString()); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } }
public async void FindTvs() { if (searchState == SearchState.Searching) { StopSearching(); } tvSearchSocket = new DatagramSocket(); tvSearchSocket.MessageReceived += TvListenCompleted; await tvSearchSocket.BindEndpointAsync(null, ""); tvSearchSocket.JoinMulticastGroup(multicastAddress); StartedSearching(); SendSSDP(); tvSearchRetryTimer = new Timer(TvSearchRetry, null, TimeSpan.FromSeconds(tvSearchRetryTimeSeconds), TimeSpan.FromMilliseconds(-1)); tvSearchTimeoutTimer = new Timer(TvSearchTimeout, null, TimeSpan.FromSeconds(tvSearchTotalTimeSeconds), TimeSpan.FromMilliseconds(-1)); searchState = SearchState.Searching; }
private async Task DataListener() { udpClient = new DatagramSocket(); udpClient.MessageReceived += Listener_MessageReceived; try { var icp = NetworkInformation.GetInternetConnectionProfile(); HostName IP = NetworkInformation.GetHostNames().SingleOrDefault(hn => hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId); Debug.Log("UDPMultiClientMiddleware asking for socket on device: " + IP.ToString()); await udpClient.BindEndpointAsync(IP, "0"); _listening = true; Debug.Log("UDPMultiClientMiddleware listening on " + IP.ToString() + ":" + udpClient.Information.LocalPort); } catch (Exception e) { Debug.Log("DATA LISTENER START EXCEPTION: " + e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } }
// Use this for initialization #if !UNITY_EDITOR async void Start() { #else void Start() { #endif m_receivedData = new SafeQueue <ReceiveDataType>(); #if !UNITY_EDITOR m_udp = new DatagramSocket(); m_udp.MessageReceived += Socket_MessageReceived; try { await m_udp.BindEndpointAsync(null, m_localPort.ToString()); } catch (IOException e) { return; } //m_udp.Control.DontFragment = true; //m_udp.Control.InboundBufferSizeInBytes = 1024 * 1024; //m_udp.Control.QualityOfService = SocketQualityOfService.LowLatency; #else m_udp = new UdpClient(m_localPort); m_udp.Client.ReceiveTimeout = 1000; m_listenThread = new Thread(new ParameterizedThreadStart(ListenThread)); m_listenThread.Start(this); #endif } // Update is called once per frame void Update() { while (m_receivedData.Count > 0) { ReceiveDataType rcv = m_receivedData.Dequeue(); //Debug.Log(rcv.data + " from " + rcv.remoteIP.ToString()); if (null != m_onReceive) { m_onReceive.Invoke(rcv.data, rcv.remoteIP.Address.ToString(), rcv.remoteIP.Port); } } }
async void Start() { if (udpEvent == null) { udpEvent = new UDPMessageEvent(); udpEvent.AddListener(UDPMessageReceived); } Debug.Log("Waiting for a connection..."); socket = new DatagramSocket(); socket.MessageReceived += Socket_MessageReceived; HostName IP = null; try { var icp = NetworkInformation.GetInternetConnectionProfile(); IP = Windows.Networking.Connectivity.NetworkInformation.GetHostNames().SingleOrDefault( hn => hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId ); await socket.BindEndpointAsync(IP, internalPort); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } if (sendPingAtStart) { SendUDPMessage(externalIP, externalPort, Encoding.UTF8.GetBytes(PingMessage)); } }
public async void init(string hostIP, int remotePort, int localPort, OscMessageHandler allMessageHandler) { AllMessageHandler = allMessageHandler; Debug.Log("Waiting for a connection..."); socket = new DatagramSocket(); socket.MessageReceived += Socket_MessageReceived; // Bind to any port Debug.Log(String.Format("{0}: UdpSocketClient created. Binding to port {1}.", this, localPort.ToString())); try { await socket.BindEndpointAsync(null, localPort.ToString()); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } }
public async Task MakeDiscoverableAsync(int metaDataPort, UPNPConfiguration config) { _ssdpDiscoveryListener = new DatagramSocket(); _ssdpDiscoveryListener.MessageReceived += _socket_MessageReceived; _webListener = new StreamSocketListener(); _webListener.ConnectionReceived += ProcessRequestAsync; _config = config; _metaDataPort = metaDataPort; try { await _webListener.BindServiceNameAsync(metaDataPort.ToString()); } catch (Exception ex) { throw new Exception("Attempt to start Web Listener Failed on Port: " + metaDataPort.ToString(), ex); } try { await _ssdpDiscoveryListener.BindEndpointAsync(null, _config.UdpListnerPort.ToString()); } catch (Exception ex) { throw new Exception("Attempt to SSDP Listener Failed on Port: " + _config.UdpListnerPort.ToString(), ex); } try { _ssdpDiscoveryListener.JoinMulticastGroup(new HostName("239.255.255.250")); } catch (Exception ex) { throw new Exception("Attempt to Join Multi Cast Group Failed", ex); } }
async void Initialize() { // indicate the start Debug.Log("Waiting for a connection..."); // initialize the socket socket = new DatagramSocket(); socket.MessageReceived += Socket_MessageReceived; // initialize the host IP HostName IP = null; // get the sender(host)'s IP try { var icp = NetworkInformation.GetInternetConnectionProfile(); IP = Windows.Networking.Connectivity.NetworkInformation.GetHostNames() .SingleOrDefault( hn => hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId); await socket.BindEndpointAsync(IP, myPort.ToString()); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } // make a message var message = "hello from " + IP; // exit the initialization Debug.Log("exit start"); }
// use this for initialization #if !UNITY_EDITOR async void Start() { #endif #if UNITY_EDITOR void Start() { #endif #if !UNITY_EDITOR Debug.Log("Waiting for a connection..."); socket = new DatagramSocket(); socket.MessageReceived += Socket_MessageReceived; try { await socket.BindEndpointAsync(null, listenPort); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } Debug.Log("exit start"); #endif } // Update is called once per frame void Update() { }
private static async Task SendUdpPing(HostName hostName) { Debug.WriteLine(DateTime.Now.TimeOfDay.ToString() + ": SendUdpPing"); string ipAddress = hostName.CanonicalName; DatagramSocket socket; if (!sockets.TryGetValue(ipAddress, out socket)) { // setup the socket for this network adapter. socket = new DatagramSocket(); socket.MessageReceived += OnDatagramMessageReceived; sockets[ipAddress] = socket; // the foscam only responds when the source port is also m_portNumber. await socket.BindEndpointAsync(hostName, m_portNumber.ToString()); } using (IOutputStream os = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), m_portNumber.ToString())) { DataWriter writer = new DataWriter(os); writer.WriteBytes(m_request); await writer.StoreAsync(); } }
// build dictionary and connect public void onStart() { #if !UNITY_EDITOR socket.MessageReceived += socket_MessageReceived; System.Diagnostics.Debug.WriteLine("Attempting to Connect..."); socket.BindEndpointAsync(host, port.ToString()); System.Diagnostics.Debug.WriteLine("Listening..."); // build dictionary foreach (string info in keys) { telemetry.Add(info, ""); } #else foreach (string info in keys) { telemetry.Add(info, ""); } // initialize network Debug.Log("Starting Client"); remoteEP = new IPEndPoint(IPAddress.Any, receivePort); client = new UdpClient(remoteEP); #endif }
/// <summary> /// Internal constructor for UDP connections /// </summary> /// <param name="connectionInfo"></param> /// <param name="defaultSendReceiveOptions"></param> /// <param name="level"></param> /// <param name="listenForIncomingPackets"></param> /// <param name="existingConnection"></param> internal UDPConnection(ConnectionInfo connectionInfo, SendReceiveOptions defaultSendReceiveOptions, UDPOptions level, bool listenForIncomingPackets, UDPConnection existingConnection = null) : base(connectionInfo, defaultSendReceiveOptions) { if (connectionInfo.ConnectionType != ConnectionType.UDP) { throw new ArgumentException("Provided connectionType must be UDP.", "connectionInfo"); } if (NetworkComms.LoggingEnabled) { NetworkComms.Logger.Trace("Creating new UDPConnection with " + connectionInfo); } if (connectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled && level != UDPOptions.None) { throw new ArgumentException("If the application layer protocol has been disabled the provided UDPOptions can only be UDPOptions.None."); } ConnectionUDPOptions = level; if (listenForIncomingPackets && existingConnection != null) { throw new Exception("Unable to listen for incoming packets if an existing client has been provided. This is to prevent possible multiple accidently listens on the same client."); } if (existingConnection == null) { if (connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any) || connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.IPv6Any)) { #if WINDOWS_PHONE || NETFX_CORE //We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only socket = new DatagramSocket(); if (listenForIncomingPackets) { socket.MessageReceived += socket_MessageReceived; } socket.BindEndpointAsync(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString()).AsTask().Wait(); #else //We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint)); #endif } else { //If this is a specific connection we link to a default end point here isIsolatedUDPConnection = true; #if WINDOWS_PHONE || NETFX_CORE if (ConnectionInfo.LocalEndPoint == null || (ConnectionInfo.LocalIPEndPoint.Address == IPAddress.Any && connectionInfo.LocalIPEndPoint.Port == 0) || (ConnectionInfo.LocalIPEndPoint.Address == IPAddress.IPv6Any && connectionInfo.LocalIPEndPoint.Port == 0)) { socket = new DatagramSocket(); if (listenForIncomingPackets) { socket.MessageReceived += socket_MessageReceived; } socket.ConnectAsync(new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask().Wait(); } else { socket = new DatagramSocket(); if (listenForIncomingPackets) { socket.MessageReceived += socket_MessageReceived; } EndpointPair pair = new EndpointPair(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString(), new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()); socket.ConnectAsync(pair).AsTask().Wait(); } #else if (ConnectionInfo.LocalEndPoint == null) { udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.RemoteEndPoint.AddressFamily)); } else { udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint)); } //By calling connect we discard packets from anything other then the provided remoteEndPoint on our localEndPoint udpClient.Connect(ConnectionInfo.RemoteIPEndPoint); #endif } #if !WINDOWS_PHONE && !NETFX_CORE //NAT traversal does not work in .net 2.0 //Mono does not seem to have implemented AllowNatTraversal method and attempting the below method call will throw an exception //if (Type.GetType("Mono.Runtime") == null) //Allow NAT traversal by default for all udp clients // udpClientThreadSafe.AllowNatTraversal(true); if (listenForIncomingPackets) { StartIncomingDataListen(); } #endif } else { if (!existingConnection.ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any)) { throw new Exception("If an existing udpClient is provided it must be unbound to a specific remoteEndPoint"); } #if WINDOWS_PHONE || NETFX_CORE //Using an exiting client allows us to send from the same port as for the provided existing connection this.socket = existingConnection.socket; #else //Using an exiting client allows us to send from the same port as for the provided existing connection this.udpClient = existingConnection.udpClient; #endif } IPEndPoint localEndPoint; #if WINDOWS_PHONE || NETFX_CORE localEndPoint = new IPEndPoint(IPAddress.Parse(socket.Information.LocalAddress.DisplayName.ToString()), int.Parse(socket.Information.LocalPort)); #else localEndPoint = udpClient.LocalIPEndPoint; #endif //We can update the localEndPoint so that it is correct if (!ConnectionInfo.LocalEndPoint.Equals(localEndPoint)) { //We should now be able to set the connectionInfo localEndPoint NetworkComms.UpdateConnectionReferenceByEndPoint(this, ConnectionInfo.RemoteIPEndPoint, localEndPoint); ConnectionInfo.UpdateLocalEndPointInfo(localEndPoint); } }
//This code will work on win phone too public override async Task <HashSet <Tuple <Uri, Uri> > > GetDeviceLocations(string schema, Func <string, string, byte[]> createSsdpRequest, Func <byte[], int, Uri> parseSsdpResponse) { var remoteIp = new HostName("239.255.255.250"); var remotePort = "1900"; // standard multicast address+port for SSDP var reqbuf = WindowsRuntimeBufferExtensions.AsBuffer( createSsdpRequest(remoteIp.RawName + ":" + remotePort, schema)); var locations = new HashSet <Tuple <Uri, Uri> >(); using (var socket = new DatagramSocket()) { socket.MessageReceived += (sender, e) => { if (e.LocalAddress.IPInformation != null && e.LocalAddress.IPInformation.NetworkAdapter.IanaInterfaceType == 24) { return; // loopback } // any loopback renderer will also report itself on the actual network, and I don't want to show duplicates using (var reader = e.GetDataReader()) { var responsebuf = new Byte[reader.UnconsumedBufferLength - 1]; reader.ReadBytes(responsebuf); if (_progress != null) { _progress.Report("Received from " + e.RemoteAddress.DisplayName + ":" + e.RemotePort + vbCrLf + Encoding.UTF8.GetString(responsebuf, 0, responsebuf.Length)); } var location = parseSsdpResponse(responsebuf, responsebuf.Length); if (location != null) { locations.Add(Tuple.Create(location, new Uri("http://" + e.LocalAddress.CanonicalName))); } } }; // CAPABILITY: PrivateNetworks #if WINDOWS_PHONE_APP ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile(); await socket.BindEndpointAsync(null, ""); #else ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile(); await socket.BindServiceNameAsync("", connectionProfile.NetworkAdapter); #endif socket.Control.OutboundUnicastHopLimit = 1; socket.JoinMulticastGroup(remoteIp); // Alas there's no WinRT equivalent of ReuseAddress using (var stream = await socket.GetOutputStreamAsync(new HostName("239.255.255.250"), remotePort)) { await stream.WriteAsync(reqbuf); await Task.Delay(20); await stream.WriteAsync(reqbuf); await Task.Delay(20); await stream.WriteAsync(reqbuf); } await Task.Delay(1200); } return(locations); }
private async Task ExecuteDiscoveryTask() { int repeatTime = EndpointController.REPEAT_DISCOVERY_TASK / 2; while (running) { Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Started Cloudlet Discovery using Multicast UDP"); retry = 0; DatagramSocket socketSent = null; DatagramSocket socketReplay = null; try { socketSent = new DatagramSocket(); await socketSent.BindEndpointAsync(null, string.Empty); socketSent.JoinMulticastGroup(ip); socketReplay = new DatagramSocket(); socketReplay.MessageReceived += SocketOnMessageReceived; await socketReplay.BindServiceNameAsync(replyCloudletPort.ToString()); using (DataWriter writer = new DataWriter(await socketSent.GetOutputStreamAsync(ip, multicastPort.ToString()))) { while (retry < 60 && running) { writer.WriteString("mpos_cloudlet_req"); await writer.StoreAsync(); await writer.FlushAsync(); await Task.Delay(500); retry++; } } } catch (IOException e) { Debug.WriteLine("## [DiscoveryCloudletMulticast]: Any problem with i/o in multicast system!\n" + e.ToString()); } finally { socketSent.Dispose(); socketReplay.Dispose(); socketSent = null; socketReplay = null; } if (running) { Debug.WriteLine(">> [DiscoveryCloudletMulticast]: Retry Discovery Cloudlet, in " + repeatTime + " ms"); await Task.Delay(repeatTime); } else { Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Finished Discovery Cloudlet"); } } }
/// <summary> /// This is the click handler for the 'StartListener' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private async void StartListener_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(ServiceNameForListener.Text)) { rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage); return; } if (CoreApplication.Properties.ContainsKey("listener")) { rootPage.NotifyUser( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } CoreApplication.Properties.Remove("serverAddress"); DatagramSocket listener = new DatagramSocket(); listener.MessageReceived += MessageReceived; if (!String.IsNullOrWhiteSpace(InboundBufferSize.Text)) { uint inboundBufferSize = 0; if (!uint.TryParse(InboundBufferSize.Text, out inboundBufferSize)) { rootPage.NotifyUser( "Please provide a positive numeric Inbound buffer size.", NotifyType.ErrorMessage); return; } try { // Running both client and server on localhost will most likely not reach the buffer limit. listener.Control.InboundBufferSizeInBytes = inboundBufferSize; } catch (ArgumentException) { rootPage.NotifyUser("Please provide a valid Inbound buffer size.", NotifyType.ErrorMessage); return; } } LocalHostItem selectedLocalHost = null; if ((BindToAddress.IsChecked == true) || (BindToAdapter.IsChecked == true)) { selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem; if (selectedLocalHost == null) { rootPage.NotifyUser("Please select an address / adapter.", NotifyType.ErrorMessage); return; } // The user selected an address. For demo purposes, we ensure that connect will be using the same // address. CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); } // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("listener", listener); // Start listen operation. try { if (BindToAny.IsChecked == true) { // Don't limit traffic to an address or an adapter. await listener.BindServiceNameAsync(ServiceNameForListener.Text); rootPage.NotifyUser("Listening", NotifyType.StatusMessage); } else if (BindToAddress.IsChecked == true) { // Try to bind to a specific address. await listener.BindEndpointAsync(selectedLocalHost.LocalHost, ServiceNameForListener.Text); rootPage.NotifyUser( "Listening on address " + selectedLocalHost.LocalHost.CanonicalName, NotifyType.StatusMessage); } else if (BindToAdapter.IsChecked == true) { // Try to limit traffic to the selected adapter. // This option will be overriden by interfaces with weak-host or forwarding modes enabled. NetworkAdapter selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter; await listener.BindServiceNameAsync(ServiceNameForListener.Text, selectedAdapter); rootPage.NotifyUser( "Listening on adapter " + selectedAdapter.NetworkAdapterId, NotifyType.StatusMessage); } } catch (Exception exception) { CoreApplication.Properties.Remove("listener"); // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
// public methods public async Task <Int32> bind(string address, Int32 port, Int32 flags) { await _socket.BindEndpointAsync(new HostName(address), port.ToString()); return(0); }
public void Connect(VpnChannel channel) { State = VpnPluginState.Connecting; LogLine("Connecting", channel); try { var transport = new DatagramSocket(); channel.AssociateTransport(transport, null); VpnContext context = null; if (channel.PlugInContext == null) { LogLine("Initializing new context", channel); channel.PlugInContext = context = new VpnContext(); } else { LogLine("Context exists", channel); context = (VpnContext)channel.PlugInContext; } transport.BindEndpointAsync(new HostName("127.0.0.1"), "9007").AsTask().ContinueWith(t => { LogLine("Binded", channel); }).Wait(); #if !DEBUG context.Init("9008"); #endif /* var rport = context.Init(transport.Information.LocalPort, str => * { * LogLine(str, channel); * return null; * }); */ var rport = "9008"; transport.ConnectAsync(new HostName("127.0.0.1"), rport).AsTask().ContinueWith(t => { LogLine("r Connected", channel); }); VpnRouteAssignment routeScope = new VpnRouteAssignment() { ExcludeLocalSubnets = true }; var inclusionRoutes = routeScope.Ipv4InclusionRoutes; // myip.ipip.net //inclusionRoutes.Add(new VpnRoute(new HostName("36.99.18.134"), 32)); // qzworld.net //inclusionRoutes.Add(new VpnRoute(new HostName("188.166.248.242"), 32)); // DNS server inclusionRoutes.Add(new VpnRoute(new HostName("1.1.1.1"), 32)); // main CIDR inclusionRoutes.Add(new VpnRoute(new HostName("172.17.0.0"), 16)); var assignment = new VpnDomainNameAssignment(); var dnsServers = new[] { // DNS servers // new HostName("192.168.1.1"), new HostName("1.1.1.1") }; assignment.DomainNameList.Add(new VpnDomainNameInfo(".", VpnDomainNameType.Suffix, dnsServers, new HostName[] { })); var now = DateTime.Now; LogLine("Starting transport", channel); channel.StartWithMainTransport( new[] { new HostName("192.168.3.1") }, null, null, routeScope, assignment, 1500u, 1512u, false, transport ); var delta = DateTime.Now - now; LogLine($"Finished starting transport in {delta.TotalMilliseconds} ms.", channel); LogLine("Connected", channel); State = VpnPluginState.Connected; } catch (Exception ex) { LogLine("Error connecting", channel); LogLine(ex.Message, channel); LogLine(ex.StackTrace, channel); State = VpnPluginState.Disconnected; } def?.Complete(); }
public async Task DiscoverBridge(TimeSpan timeOut) { var multicastIP = new HostName("239.255.255.250"); var foundBridge = false; using (var socket = new DatagramSocket()) { socket.MessageReceived += async(sender, args) => { var reader = args.GetDataReader(); var bytesRemaining = reader.UnconsumedBufferLength; foreach (var line in reader.ReadString(bytesRemaining).Split(new String[1] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) { if (line.StartsWith("LOCATION")) { var address = line.Split(new char[1] { ':' }, 2)[1]; var message = await _client.GetAsync(address); if (message.IsSuccessStatusCode) { var messageContent = await message.Content.ReadAsStringAsync(); var buffer = Encoding.UTF8.GetBytes(messageContent); } } } foundBridge = true; }; await socket.BindEndpointAsync(null, string.Empty); socket.JoinMulticastGroup(multicastIP); while (true) { foundBridge = false; using (var stream = await socket.GetOutputStreamAsync(multicastIP, "1900")) using (var writer = new DataWriter(stream)) { var request = new StringBuilder(); request.AppendLine("M-SEARCH * HTTP/1.1"); request.AppendLine("HOST: 239.255.255.250:1900"); request.AppendLine("MAN: ssdp:discover"); request.AppendLine("MX: 3"); request.AppendLine("ST: ssdp:all"); writer.WriteString(request.ToString()); await writer.StoreAsync(); if (timeOut > TimeSpan.Zero) { await Task.Delay(timeOut); } if (foundBridge) { break; } } } } }
public void Connect(VpnChannel channel) { State = VpnPluginState.Connecting; DebugLogger.Logger = s => { channel.LogDiagnosticMessage(s); }; DebugLogger.Log("Starting connection to VPN tunnel"); try { var transport = new DatagramSocket(); channel.AssociateTransport(transport, null); DebugLogger.Log("Initializing context"); #if !YT_MOCK var configPath = AdapterConfig.GetDefaultConfigFilePath(); if (string.IsNullOrEmpty(configPath)) { channel.TerminateConnection("Default server configuration not set. Please launch YtFlow app and select a server configuration as default."); return; } try { var config = AdapterConfig.GetConfigFromFilePath(configPath); if (config == null) { channel.TerminateConnection("Could not read server configuration."); return; } } catch (Exception ex) { channel.TerminateConnection("Error reading server configuration: " + ex.ToString()); return; } #endif DebugLogger.Log("Config read, binding endpoint"); if (!transport.BindEndpointAsync(new HostName("127.0.0.1"), string.Empty).AsTask().ContinueWith(t => { if (t.IsFaulted || t.IsCanceled) { DebugLogger.Log("Error binding endpoint: " + t.Exception.ToString()); return(false); } else { DebugLogger.Log("Binded"); return(true); } }).Result) { return; } DebugLogger.Log("Endpoint binded, init context"); var rport = context.Init(int.Parse(transport.Information.LocalPort)).ToString(); DebugLogger.Log("Context initialized"); /* var rport = context.Init(transport.Information.LocalPort, str => * { * LogLine(str, channel); * return null; * }); */ DebugLogger.Log("Connecting to local packet processor"); if (!transport.ConnectAsync(new HostName("127.0.0.1"), rport).AsTask().ContinueWith(t => { if (t.IsFaulted || t.IsCanceled) { channel.TerminateConnection("Error connecting to local packet processor: " + t.Exception.ToString()); DebugLogger.Log("Local packet processor connected"); return(false); } else { return(true); } }).Result) { return; } DebugLogger.Log("Connected to local packet processor"); VpnRouteAssignment routeScope = new VpnRouteAssignment() { ExcludeLocalSubnets = true }; var inclusionRoutes = routeScope.Ipv4InclusionRoutes; // DNS server inclusionRoutes.Add(new VpnRoute(new HostName("1.1.1.1"), 32)); // main CIDR inclusionRoutes.Add(new VpnRoute(new HostName("11.17.0.0"), 16)); // proxy inclusionRoutes.Add(new VpnRoute(new HostName("172.17.255.0"), 24)); var assignment = new VpnDomainNameAssignment(); assignment.DomainNameList.Add(new VpnDomainNameInfo( ".", VpnDomainNameType.Suffix, new[] { new HostName("1.1.1.1") }, Array.Empty <HostName>())); var now = DateTime.Now; DebugLogger.Log("Starting transport"); channel.StartWithMainTransport( new[] { new HostName("192.168.3.1") }, null, null, routeScope, assignment, 1500u, 1512u, false, transport ); var delta = DateTime.Now - now; _ = context.u.SendAsync(new byte[] { 0 }, 1, context.pluginEndpoint); DebugLogger.Log($"Transport started in {delta.TotalMilliseconds} ms."); State = VpnPluginState.Connected; } catch (Exception ex) { var msg = "Error connecting to VPN tunnel: " + ex.ToString(); channel.TerminateConnection(msg); DebugLogger.Log(msg); State = VpnPluginState.Disconnected; } }
public void Connect(VpnChannel channel) { State = VpnPluginState.Connecting; LogLine("Connecting", channel); try { var transport = new DatagramSocket(); channel.AssociateTransport(transport, null); DebugVpnContext context = null; if (channel.PlugInContext == null) { LogLine("Initializing new context", channel); #if YT_MOCK channel.PlugInContext = context = new DebugVpnContext(); #else var configPath = AdapterConfig.GetDefaultConfigFilePath(); if (string.IsNullOrEmpty(configPath)) { channel.TerminateConnection("Config not set"); return; } try { var config = AdapterConfig.GetConfigFromFilePath(configPath); if (config == null) { throw new Exception("Cannot read config file."); } } catch (Exception ex) { channel.TerminateConnection("Error reading config file:" + ex.Message); } channel.PlugInContext = context = new DebugVpnContext("9008"); #endif } else { LogLine("Context exists", channel); context = (DebugVpnContext)channel.PlugInContext; } transport.BindEndpointAsync(new HostName("127.0.0.1"), "9007").AsTask().ContinueWith(t => { LogLine("Binded", channel); }).Wait(); #if !YT_MOCK context.Init(); #endif /* var rport = context.Init(transport.Information.LocalPort, str => * { * LogLine(str, channel); * return null; * }); */ var rport = "9008"; transport.ConnectAsync(new HostName("127.0.0.1"), rport).AsTask().ContinueWith(t => { LogLine("r Connected", channel); }); VpnRouteAssignment routeScope = new VpnRouteAssignment() { ExcludeLocalSubnets = true }; var inclusionRoutes = routeScope.Ipv4InclusionRoutes; // myip.ipip.net //inclusionRoutes.Add(new VpnRoute(new HostName("36.99.18.134"), 32)); // qzworld.net //inclusionRoutes.Add(new VpnRoute(new HostName("188.166.248.242"), 32)); // DNS server inclusionRoutes.Add(new VpnRoute(new HostName("1.1.1.1"), 32)); // main CIDR inclusionRoutes.Add(new VpnRoute(new HostName("172.17.0.0"), 16)); var assignment = new VpnDomainNameAssignment(); var dnsServers = new[] { // DNS servers new HostName("1.1.1.1"), }; assignment.DomainNameList.Add(new VpnDomainNameInfo(".", VpnDomainNameType.Suffix, dnsServers, new HostName[] { })); var now = DateTime.Now; LogLine("Starting transport", channel); channel.StartWithMainTransport( new[] { new HostName("192.168.3.1") }, null, null, routeScope, assignment, 1500u, 1512u, false, transport ); var delta = DateTime.Now - now; LogLine($"Finished starting transport in {delta.TotalMilliseconds} ms.", channel); LogLine("Connected", channel); State = VpnPluginState.Connected; } catch (Exception ex) { LogLine("Error connecting", channel); LogLine(ex.Message, channel); LogLine(ex.StackTrace, channel); channel.TerminateConnection("Cannot connect to local tunnel"); State = VpnPluginState.Disconnected; } }