public static List <IPEndPoint> ParseIPSockets(XmlNode socketNodes) { List <IPEndPoint> endPoints = new List <IPEndPoint>(); List <IPAddress> localAddresses = GetLocalIPv4Addresses(); foreach (XmlNode socketNode in socketNodes.ChildNodes) { string socketString = socketNode.InnerText; Logger.Logger.Debug("Parsing end point from socket string " + socketString + "."); int port = IPSocket.ParsePortFromSocket(socketString); if (socketString.StartsWith(ALL_LOCAL_IPADDRESSES_KEY)) { foreach (IPAddress ipAddress in localAddresses) { endPoints.Add(new IPEndPoint(ipAddress, port)); } } else { endPoints.Add(IPSocket.ParseSocketString(socketString)); } } return(endPoints); }
private static IEnumerable <SIPEndPoint> GetSIPEndPoints(string sipSocketString, SIPProtocolsEnum sipProtocol, int overridePort) { if (sipSocketString == null) { return(null); } int port; if (overridePort > 0) { port = overridePort; } else { port = IPSocket.ParsePortFromSocket(sipSocketString); if (port == 0) { port = (sipProtocol == SIPProtocolsEnum.tls) ? m_defaultSIPTLSPort : m_defaultSIPPort; } } if (sipSocketString.StartsWith(m_allIPAddresses)) { return(m_localIPAddresses.Select(x => new SIPEndPoint(sipProtocol, new IPEndPoint(x, port)))); } var ipAddress = IPAddress.Parse(IPSocket.ParseHostFromSocket(sipSocketString)); return(new List <SIPEndPoint> { new SIPEndPoint(sipProtocol, new IPEndPoint(ipAddress, port)) }); }
public void ParsePortFromSocketTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); int port = IPSocket.ParsePortFromSocket("localhost:5060"); Console.WriteLine("port=" + port); Assert.IsTrue(port == 5060, "The port was not parsed correctly."); }
public void ParsePortFromSocketTest() { logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name); int port = IPSocket.ParsePortFromSocket("localhost:5060"); logger.LogDebug("port=" + port); Assert.True(port == 5060, "The port was not parsed correctly."); }
private static IEnumerable <SIPEndPoint> GetSIPEndPoints(string sipSocketString, SIPProtocolsEnum sipProtocol, int overridePort) { if (sipSocketString == null) { return(null); } int port; if (overridePort > 0) { port = overridePort; } else { port = IPSocket.ParsePortFromSocket(sipSocketString); if (port == 0) { port = (sipProtocol == SIPProtocolsEnum.tls) ? m_defaultSIPTLSPort : m_defaultSIPPort; } } if (sipSocketString.StartsWith(ALL_LOCAL_IPADDRESSES_KEY)) { return(new List <SIPEndPoint> { new SIPEndPoint(sipProtocol, new IPEndPoint(IPAddress.Any, port)) }); } else { var ipAddress = IPAddress.Parse(IPSocket.ParseHostFromSocket(sipSocketString)); return(new List <SIPEndPoint> { new SIPEndPoint(sipProtocol, new IPEndPoint(ipAddress, port)) }); } }
public void Start(string url) { _url = url; Match urlMatch = Regex.Match(url, @"rtsp://(?<hostname>\S+?)/", RegexOptions.IgnoreCase); if (!urlMatch.Success) { throw new ApplicationException("The URL provided to the RTSP client was not recognised, " + url + "."); } else { string hostname = urlMatch.Result("${hostname}"); int port = RTSP_PORT; if (hostname.Contains(':')) { port = IPSocket.ParsePortFromSocket(hostname); hostname = IPSocket.ParseHostFromSocket(hostname); } logger.Debug("RTSP client connecting to " + hostname + ", port " + port + "."); _rtspConnection = new TcpClient(hostname, port); _rtspStream = _rtspConnection.GetStream(); _rtspSession = new RTSPSession(); _rtspSession.RTPPayloadHeaderLength = _rtpPayloadHeaderLength; _rtspSession.ReservePorts(); _rtspSession.OnRTPQueueFull += RTPQueueFull; RTSPRequest rtspRequest = new RTSPRequest(RTSPMethodsEnum.SETUP, url); RTSPHeader rtspHeader = new RTSPHeader(_cseq++, null); rtspHeader.Transport = new RTSPTransportHeader() { ClientRTPPortRange = _rtspSession.RTPPort + "-" + _rtspSession.ControlPort }; rtspRequest.Header = rtspHeader; string rtspReqStr = rtspRequest.ToString(); RTSPMessage rtspMessage = null; Debug.WriteLine(rtspReqStr); byte[] rtspRequestBuffer = Encoding.UTF8.GetBytes(rtspReqStr); _rtspStream.Write(rtspRequestBuffer, 0, rtspRequestBuffer.Length); byte[] buffer = new byte[2048]; int bytesRead = _rtspStream.Read(buffer, 0, 2048); if (bytesRead > 0) { Debug.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead)); rtspMessage = RTSPMessage.ParseRTSPMessage(buffer, null, null); if (rtspMessage.RTSPMessageType == RTSPMessageTypesEnum.Response) { var setupResponse = RTSPResponse.ParseRTSPResponse(rtspMessage); if (setupResponse.Status == RTSPResponseStatusCodesEnum.OK) { _rtspSession.SessionID = setupResponse.Header.Session; _rtspSession.RemoteEndPoint = new IPEndPoint( (_rtspConnection.Client.RemoteEndPoint as IPEndPoint).Address, setupResponse.Header.Transport.GetServerRTPPort()); _rtspSession.Start(); logger.Debug("RTSP Response received to SETUP: " + setupResponse.Status + ", session ID " + _rtspSession.SessionID + ", server RTP endpoint " + _rtspSession.RemoteEndPoint + "."); if (OnSetupSuccess != null) { OnSetupSuccess(this); } } else { logger.Warn("RTSP Response received to SETUP: " + setupResponse.Status + "."); throw new ApplicationException("An error response of " + setupResponse.Status + " was received for an RTSP setup request."); } } } else { throw new ApplicationException( "Zero bytes were read from the RTSP client socket in response to a SETUP request."); } } }
// TODO: Remove this nasty code duplication with ResolveSIPService! public static async Task <SIPDNSLookupResult> ResolveAsync(SIPURI sipURI, bool?preferIPv6 = null) { try { if (sipURI == null) { throw new ArgumentNullException("sipURI", "Cannot resolve SIP service on a null URI."); } if (IPSocket.TryParseIPEndPoint(sipURI.MAddrOrHost, out var ipEndPoint)) { // Target is an IP address, no DNS lookup required. SIPDNSLookupEndPoint sipLookupEndPoint = new SIPDNSLookupEndPoint(new SIPEndPoint(sipURI.Protocol, ipEndPoint), 0); SIPDNSLookupResult result = new SIPDNSLookupResult(sipURI); result.AddLookupResult(sipLookupEndPoint); return(result); } else { string host = sipURI.MAddrOrHostAddress; //int port = IPSocket.ParsePortFromSocket(host); int port = sipURI.Protocol != SIPProtocolsEnum.tls ? m_defaultSIPPort : m_defaultSIPSPort; if (preferIPv6 == null) { preferIPv6 = SIPDNSManager.PreferIPv6NameResolution; } bool explicitPort = false; try { //Parse returns true if sipURI.Host can be parsed as an ipaddress bool parseresult = SIPSorcery.Sys.IPSocket.Parse(sipURI.MAddrOrHost, out host, out port); explicitPort = port >= 0; if (!explicitPort) { //port = (sipURI.Scheme == SIPSchemesEnum.sip) ? m_defaultSIPPort : m_defaultSIPSPort; port = sipURI.Protocol != SIPProtocolsEnum.tls ? m_defaultSIPPort : m_defaultSIPSPort; } if (parseresult == true) { IPAddress hostIP = IPAddress.Parse(host); SIPDNSLookupEndPoint sipLookupEndPoint = new SIPDNSLookupEndPoint(new SIPEndPoint(sipURI.Protocol, new IPEndPoint(hostIP, port)), 0); SIPDNSLookupResult result = new SIPDNSLookupResult(sipURI); result.AddLookupResult(sipLookupEndPoint); return(result); } } catch (Exception ex) { SIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Unknown, SIPMonitorEventTypesEnum.DNS, "Exception SIPDNSManager ResolveSIPService (" + sipURI.ToString() + "). " + ex, null)); //rj2: if there is a parsing exception, then fallback to original sipsorcery parsing mechanism port = IPSocket.ParsePortFromSocket(sipURI.Host); explicitPort = port > 0; //if(Regex.Match(host, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").Success) if (SIPSorcery.Sys.IPSocket.IsIPAddress(host)) { // Target is an IP address, no DNS lookup required. IPAddress hostIP = IPAddress.Parse(host); SIPDNSLookupEndPoint sipLookupEndPoint = new SIPDNSLookupEndPoint(new SIPEndPoint(sipURI.Protocol, new IPEndPoint(hostIP, port)), 0); SIPDNSLookupResult result = new SIPDNSLookupResult(sipURI); result.AddLookupResult(sipLookupEndPoint); return(result); } } if (!explicitPort) { //port = (sipURI.Scheme == SIPSchemesEnum.sip) ? m_defaultSIPPort : m_defaultSIPSPort; port = sipURI.Protocol != SIPProtocolsEnum.tls ? m_defaultSIPPort : m_defaultSIPSPort; } if (host.Contains(".") == false || IPSocket.ParseHostFromSocket(host).EndsWith(MDNS_TLD)) { string hostOnly = IPSocket.ParseHostFromSocket(host); // If host is not fully qualified then assume there's no point using NAPTR or SRV record look ups and go straight to A's. if (hostOnly.ToLower() == System.Net.Dns.GetHostName()?.ToLower()) { // The lookup is for the current machine. var addressList = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList; if (addressList?.Length == 0) { return(new SIPDNSLookupResult(sipURI, $"Failed to resolve local machine hostname.")); } else { // Preference for IPv4 IP address for local host name lookup. IPAddress firstAddress = addressList.Where(x => x.AddressFamily == (preferIPv6 == true ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork)).FirstOrDefault() ?? addressList.FirstOrDefault(); SIPEndPoint resultEp = new SIPEndPoint(sipURI.Protocol, new IPEndPoint(firstAddress, port)); return(new SIPDNSLookupResult(sipURI, resultEp)); } } else { return(await Task.Run(() => DNSNameRecordLookup(hostOnly, port, false, sipURI, null, preferIPv6)).ConfigureAwait(false)); } } else if (explicitPort) { // If target is a hostname with an explicit port then SIP lookup rules state to use DNS lookup for A or AAAA record. host = host.Substring(0, host.LastIndexOf(':')); return(await Task.Run(() => DNSNameRecordLookup(host, port, false, sipURI, null, preferIPv6)).ConfigureAwait(false)); } else { // Target is a hostname with no explicit port, use the whole NAPTR->SRV->A lookup procedure. SIPDNSLookupResult sipLookupResult = new SIPDNSLookupResult(sipURI); // Do without the NAPTR lookup for the time being. Very few organisations appear to use them and it can cost up to 2.5s to get a failed resolution. //rj2: uncomment this section for telekom 1TR118 lookup SIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Unknown, SIPMonitorEventTypesEnum.DNS, "SIP DNS full lookup requested for " + sipURI.ToString() + ".", null)); DNSNAPTRRecordLookup(host, false, ref sipLookupResult); if (sipLookupResult.Pending) { if (!m_inProgressSIPServiceLookups.Contains(sipURI.ToString())) { m_inProgressSIPServiceLookups.Add(sipURI.ToString()); //ThreadPool.QueueUserWorkItem(delegate { ResolveSIPService(sipURI, false); }); System.Threading.ThreadPool.QueueUserWorkItem((obj) => ResolveSIPService(sipURI, false, preferIPv6)); } return(sipLookupResult); } return(await Task.Run(() => { DNSSRVRecordLookup(sipURI.Scheme, sipURI.Protocol, host, false, ref sipLookupResult); if (sipLookupResult.Pending) { //logger.LogDebug("SIPDNSManager SRV lookup for " + host + " is pending."); return sipLookupResult; } else { //logger.LogDebug("SIPDNSManager SRV lookup for " + host + " is final."); // Add some custom logic to cope with sips SRV records using _sips._tcp (e.g. free.call.ciscospark.com). // By default only _sips._tls SRV records are checked for. THis block adds an additional check for _sips._tcp SRV records. //if ((sipLookupResult.SIPSRVResults == null || sipLookupResult.SIPSRVResults.Count == 0) && sipURI.Scheme == SIPSchemesEnum.sips) //{ // DNSSRVRecordLookup(sipURI.Scheme, SIPProtocolsEnum.tcp, host, async, ref sipLookupResult); // SIPDNSServiceResult nextSRVRecord = sipLookupResult.GetNextUnusedSRV(); // int lookupPort = (nextSRVRecord != null) ? nextSRVRecord.Port : port; // return DNSARecordLookup(nextSRVRecord, host, lookupPort, async, sipLookupResult.URI); //} //else //{ // SIPDNSServiceResult nextSRVRecord = sipLookupResult.GetNextUnusedSRV(); // int lookupPort = (nextSRVRecord != null) ? nextSRVRecord.Port : port; // return DNSARecordLookup(nextSRVRecord, host, lookupPort, false, sipLookupResult.URI); //} // The SRV record can indicate the SIP server is using a non-standard port. SIPDNSServiceResult nextSRVRecord = sipLookupResult.GetNextUnusedSRV(); int lookupPort = (nextSRVRecord != null) ? nextSRVRecord.Port : port; return DNSNameRecordLookup(host, lookupPort, false, sipLookupResult.URI, ref sipLookupResult, preferIPv6); } }).ConfigureAwait(false)); } } } catch (Exception excp) { logger.LogError("Exception SIPDNSManager ResolveSIPService (" + sipURI.ToString() + "). " + excp.Message); m_inProgressSIPServiceLookups.Remove(sipURI.ToString()); return(new SIPDNSLookupResult(sipURI, excp.Message)); } }
public static SIPDNSLookupResult ResolveSIPService(SIPURI sipURI, bool async) { try { if (sipURI == null) { throw new ArgumentNullException("sipURI", "Cannot resolve SIP service on a null URI."); } if (IPSocket.TryParseIPEndPoint(sipURI.Host, out var ipEndPoint)) { // Target is an IP address, no DNS lookup required. SIPDNSLookupEndPoint sipLookupEndPoint = new SIPDNSLookupEndPoint(new SIPEndPoint(sipURI.Protocol, ipEndPoint), 0); SIPDNSLookupResult result = new SIPDNSLookupResult(sipURI); result.AddLookupResult(sipLookupEndPoint); return(result); } else { string host = sipURI.Host; int port = IPSocket.ParsePortFromSocket(sipURI.Host); bool explicitPort = (port != 0); if (!explicitPort) { port = (sipURI.Scheme == SIPSchemesEnum.sip) ? m_defaultSIPPort : m_defaultSIPSPort; } if (host.Contains(".") == false) { string hostOnly = IPSocket.ParseHostFromSocket(host); // If host is not fully qualified then assume there's no point using NAPTR or SRV record look ups and go straight to A's. if (hostOnly.ToLower() == System.Net.Dns.GetHostName()?.ToLower()) { // The lookup is for the current machine. var addressList = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList; if (addressList?.Length == 0) { return(new SIPDNSLookupResult(sipURI, $"Failed to resolve local machine hostname.")); } else { // Preference for IPv4 IP address for local host anem lookup. IPAddress firstAddress = addressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault() ?? addressList.FirstOrDefault(); SIPEndPoint resultEp = new SIPEndPoint(sipURI.Protocol, new IPEndPoint(firstAddress, port)); return(new SIPDNSLookupResult(sipURI, resultEp)); } } else { return(DNSARecordLookup(hostOnly, port, async, sipURI)); } } else if (explicitPort) { // If target is a hostname with an explicit port then SIP lookup rules state to use DNS lookup for A or AAAA record. host = host.Substring(0, host.LastIndexOf(':')); return(DNSARecordLookup(host, port, async, sipURI)); } else { // Target is a hostname with no explicit port, use the whole NAPTR->SRV->A lookup procedure. SIPDNSLookupResult sipLookupResult = new SIPDNSLookupResult(sipURI); // Do without the NAPTR lookup for the time being. Very few organisations appear to use them and it can cost up to 2.5s to get a failed resolution. /*SIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Unknown, SIPMonitorEventTypesEnum.DNS, "SIP DNS full lookup requested for " + sipURI.ToString() + ".", null)); * DNSNAPTRRecordLookup(host, async, ref sipLookupResult); * if (sipLookupResult.Pending) * { * if (!m_inProgressSIPServiceLookups.Contains(sipURI.ToString())) * { * m_inProgressSIPServiceLookups.Add(sipURI.ToString()); * ThreadPool.QueueUserWorkItem(delegate { ResolveSIPService(sipURI, false); }); * } * return sipLookupResult; * }*/ DNSSRVRecordLookup(sipURI.Scheme, sipURI.Protocol, host, async, ref sipLookupResult); if (sipLookupResult.Pending) { //logger.LogDebug("SIPDNSManager SRV lookup for " + host + " is pending."); return(sipLookupResult); } else { //logger.LogDebug("SIPDNSManager SRV lookup for " + host + " is final."); // Add some custom logic to cope with sips SRV records using _sips._tcp (e.g. free.call.ciscospark.com). // By default only _sips._tls SRV records are checked for. THis block adds an additional check for _sips._tcp SRV records. //if ((sipLookupResult.SIPSRVResults == null || sipLookupResult.SIPSRVResults.Count == 0) && sipURI.Scheme == SIPSchemesEnum.sips) //{ // DNSSRVRecordLookup(sipURI.Scheme, SIPProtocolsEnum.tcp, host, async, ref sipLookupResult); // SIPDNSServiceResult nextSRVRecord = sipLookupResult.GetNextUnusedSRV(); // int lookupPort = (nextSRVRecord != null) ? nextSRVRecord.Port : port; // return DNSARecordLookup(nextSRVRecord, host, lookupPort, async, sipLookupResult.URI); //} //else //{ SIPDNSServiceResult nextSRVRecord = sipLookupResult.GetNextUnusedSRV(); int lookupPort = (nextSRVRecord != null) ? nextSRVRecord.Port : port; return(DNSARecordLookup(nextSRVRecord, host, lookupPort, async, sipLookupResult.URI)); //} } } } } catch (Exception excp) { logger.LogError("Exception SIPDNSManager ResolveSIPService (" + sipURI.ToString() + "). " + excp.Message); m_inProgressSIPServiceLookups.Remove(sipURI.ToString()); return(new SIPDNSLookupResult(sipURI, excp.Message)); } }
public static SIPDNSLookupResult ResolveSIPService(SIPURI sipURI, bool async) { try { if (sipURI == null) { throw new ArgumentNullException("sipURI", "Cannot resolve SIP service on a null URI."); } if (IPSocket.TryParseIPEndPoint(sipURI.Host, out var ipEndPoint)) { // Target is an IP address, no DNS lookup required. //IPAddress hostIP = IPAddress.Parse(host); SIPDNSLookupEndPoint sipLookupEndPoint = new SIPDNSLookupEndPoint(new SIPEndPoint(sipURI.Protocol, ipEndPoint), 0); SIPDNSLookupResult result = new SIPDNSLookupResult(sipURI); result.AddLookupResult(sipLookupEndPoint); return(result); } else { string host = sipURI.Host; int port = IPSocket.ParsePortFromSocket(sipURI.Host); bool explicitPort = (port != 0); if (!explicitPort) { port = (sipURI.Scheme == SIPSchemesEnum.sip) ? m_defaultSIPPort : m_defaultSIPSPort; } if (explicitPort) { host = host.Substring(0, host.LastIndexOf(':')); // Target is a hostname with an explicit port, DNS lookup for A or AAAA record. return(DNSARecordLookup(host, port, async, sipURI)); } else { // Target is a hostname with no explicit port, use the whole NAPTR->SRV->A lookup procedure. SIPDNSLookupResult sipLookupResult = new SIPDNSLookupResult(sipURI); // Do without the NAPTR lookup for the time being. Very few organisations appear to use them and it can cost up to 2.5s to get a failed resolution. /*SIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Unknown, SIPMonitorEventTypesEnum.DNS, "SIP DNS full lookup requested for " + sipURI.ToString() + ".", null)); * DNSNAPTRRecordLookup(host, async, ref sipLookupResult); * if (sipLookupResult.Pending) * { * if (!m_inProgressSIPServiceLookups.Contains(sipURI.ToString())) * { * m_inProgressSIPServiceLookups.Add(sipURI.ToString()); * ThreadPool.QueueUserWorkItem(delegate { ResolveSIPService(sipURI, false); }); * } * return sipLookupResult; * }*/ DNSSRVRecordLookup(sipURI.Scheme, sipURI.Protocol, host, async, ref sipLookupResult); if (sipLookupResult.Pending) { //logger.LogDebug("SIPDNSManager SRV lookup for " + host + " is pending."); return(sipLookupResult); } else { //logger.LogDebug("SIPDNSManager SRV lookup for " + host + " is final."); // Add some custom logic to cope with sips SRV records using _sips._tcp (e.g. free.call.ciscospark.com). // By default only _sips._tls SRV records are checked for. THis block adds an additional check for _sips._tcp SRV records. //if ((sipLookupResult.SIPSRVResults == null || sipLookupResult.SIPSRVResults.Count == 0) && sipURI.Scheme == SIPSchemesEnum.sips) //{ // DNSSRVRecordLookup(sipURI.Scheme, SIPProtocolsEnum.tcp, host, async, ref sipLookupResult); // SIPDNSServiceResult nextSRVRecord = sipLookupResult.GetNextUnusedSRV(); // int lookupPort = (nextSRVRecord != null) ? nextSRVRecord.Port : port; // return DNSARecordLookup(nextSRVRecord, host, lookupPort, async, sipLookupResult.URI); //} //else //{ SIPDNSServiceResult nextSRVRecord = sipLookupResult.GetNextUnusedSRV(); int lookupPort = (nextSRVRecord != null) ? nextSRVRecord.Port : port; return(DNSARecordLookup(nextSRVRecord, host, lookupPort, async, sipLookupResult.URI)); //} } } } } catch (Exception excp) { logger.LogError("Exception SIPDNSManager ResolveSIPService (" + sipURI.ToString() + "). " + excp.Message); m_inProgressSIPServiceLookups.Remove(sipURI.ToString()); return(new SIPDNSLookupResult(sipURI, excp.Message)); } }