//--------------- SENDING MESSAGES ----------------------------------------- /** * Sends the specified stun message through the specified access point. * @param stunMessage the message to send * @param apDescriptor the access point to use to send the message * @param address the destination of the message. * @throws StunException if message encoding fails, ILLEGAL_ARGUMENT if the * apDescriptor references an access point that had not been installed, * NETWORK_ERROR if an error occurs while sending message bytes through the * network socket. */ public virtual void SendMessage(Message stunMessage, NetAccessPointDescriptor apDescriptor, StunAddress address) { byte[] bytes = stunMessage.Encode(); NetAccessPoint ap = (NetAccessPoint)netAccessPoints[apDescriptor]; if (ap == null) { throw new StunException( StunException.ILLEGAL_ARGUMENT, "The specified access point had not been installed."); } try { ap.SendMessage(bytes, address); } catch (Exception ex) { throw new StunException(StunException.NETWORK_ERROR, "An Exception occurred while sending message bytes " + "through a network socket!", ex); } }
/** * Sends a binding request to the specified server address with only change * port flag set to true and change IP flag - to false. * @param serverAddress the address where to send the bindingRequest. * @return The returned message encapsulating event or null if no message * was received. * @throws StunException if an exception occurs while sending the messge */ private StunMessageEvent doTestIII(StunAddress serverAddress) { Request request = MessageFactory.CreateBindingRequest(); ChangeRequestAttribute changeRequest = (ChangeRequestAttribute)request.GetAttribute(Attribute.CHANGE_REQUEST); changeRequest.SetChangeIpFlag(false); changeRequest.SetChangePortFlag(true); StunMessageEvent evt = requestSender.SendRequestAndWaitForResponse(request, serverAddress); #if false if (evt != null) { System.oout.println("Test III res=" + evt.getRemoteAddress().toString() + " - " + evt.getRemoteAddress().getHostName()); } else { Console.WriteLine("NO RESPONSE received to Test III."); } #endif return(evt); }
/** * Creates a BindingResponse assigning the specified values to mandatory * headers. * * @param mappedAddress the address to assign the mappedAddressAttribute * @param sourceAddress the address to assign the sourceAddressAttribute * @param changedAddress the address to assign the changedAddressAttribute * @return a BindingResponse assigning the specified values to mandatory * headers. * @throws StunException ILLEGAL_ARGUMENT */ public static Response CreateBindingResponse(StunAddress mappedAddress, StunAddress sourceAddress, StunAddress changedAddress) { Response bindingResponse = new Response(); bindingResponse.SetMessageType(Message.BINDING_RESPONSE); //mapped address MappedAddressAttribute mappedAddressAttribute = AttributeFactory.CreateMappedAddressAttribute(mappedAddress); //source address SourceAddressAttribute sourceAddressAttribute = AttributeFactory.CreateSourceAddressAttribute(sourceAddress); //changed address ChangedAddressAttribute changedAddressAttribute = AttributeFactory.CreateChangedAddressAttribute(changedAddress); bindingResponse.AddAttribute(mappedAddressAttribute); bindingResponse.AddAttribute(sourceAddressAttribute); bindingResponse.AddAttribute(changedAddressAttribute); return(bindingResponse); }
//---------- main /** * Runs the discoverer and shows a message dialog with the returned report. * @param args args[0] - stun server address, args[1] - port. in the case of * no args - defaults are provided. * @throws java.lang.Exception if an exception occurrs during the discovery * process. */ #if false public static void main(String[] args) { StunAddress localAddr = null; StunAddress serverAddr = null; if (args.Length == 4) { localAddr = new StunAddress(args[2], Integer.valueOf(args[3]).intValue()); serverAddr = new StunAddress(args[0], Integer.valueOf(args[1]).intValue()); } else { localAddr = new StunAddress(InetAddress.getLocalHost(), 5678); serverAddr = new StunAddress("stun01bak.sipphone.com.", 3479); } NetworkConfigurationDiscoveryProcess addressDiscovery = new NetworkConfigurationDiscoveryProcess(localAddr, serverAddr); addressDiscovery.start(); StunDiscoveryReport report = addressDiscovery.determineAddress(); System.oout.println(report); // javax.swing.JOptionPane.showMessageDialog( // null, // report.toString(), // "Stun Discovery Process", // javax.swing.JOptionPane.INFORMATION_MESSAGE); System.exit(0); }
/** * Constructs a StunMessageEvent according to the specified message. * @param source the access point that received the message * @param message the message itself * @param remoteAddress the address that sent the message */ public StunMessageEvent(NetAccessPointDescriptor source, Message message, StunAddress remoteAddress) { this.message = message; this.remoteAddress = remoteAddress; }
/** * Creates a listening point from the following address and attempts to * discover how it is mapped so that using inside the application is possible. * @param address the [address]:[port] pair where ther request should be * sent from. * @return a StunAddress object containing the mapped address or null if * discovery failed. * @throws StunException if something fails along the way. */ public virtual StunAddress GetMappingFor(StunAddress address) { NetAccessPointDescriptor apDesc = new NetAccessPointDescriptor(address); stunStack.InstallNetAccessPoint(apDesc); requestSender = new BlockingRequestSender(stunProvider, apDesc); StunMessageEvent evt = null; try { evt = requestSender.SendRequestAndWaitForResponse( MessageFactory.CreateBindingRequest(), serverAddress); } finally { //free the port to allow the application to use it. stunStack.RemoveNetAccessPoint(apDesc); } if (evt != null) { Response res = (Response)evt.GetMessage(); MappedAddressAttribute maAtt = (MappedAddressAttribute) res.GetAttribute(Attribute.MAPPED_ADDRESS); if (maAtt != null) { StunAddress sa = maAtt.GetAddress(); return(sa); } } return(null); }
CreateChangedAddressAttribute(StunAddress address) { ChangedAddressAttribute attribute = new ChangedAddressAttribute(); attribute.SetAddress(address); return(attribute); }
//------------------------------------ MAPPED ADDRESS -------------------------- /** * Creates a MappedAddressAttribute of the specified type and with the * specified address and port * @param address the address value of the address attribute * @return the newly created address attribute. */ public static MappedAddressAttribute CreateMappedAddressAttribute( StunAddress address) { MappedAddressAttribute attribute = new MappedAddressAttribute(); attribute.SetAddress(address); return(attribute); }
//------------------------------------ REFLECTED FROM -------------------------- /** * Creates a ReflectedFromAddressAttribute of the specified type and with * the specified address and port * @param address the address value of the address attribute * @return the newly created address attribute. */ public static ReflectedFromAttribute CreateReflectedFromAttribute( StunAddress address) { ReflectedFromAttribute attribute = new ReflectedFromAttribute(); attribute.SetAddress(address); return(attribute); }
/** * Does the message parsing. */ public virtual void Run() { //add an extra try/catch block that handles uncatched errors and helps avoid //having dead threads in our pools. try { while (isRunning) { RawMessage rawMessage = null; rawMessage = messageQueue.Remove(); // were we asked to stop? if (!IsRunning()) { return; } //anything to parse? if (rawMessage == null) { continue; } Message stunMessage = null; try { stunMessage = Message.Decode(rawMessage.GetBytes(), 0, rawMessage.GetMessageLength()); } catch (StunException ex) { errorHandler.HandleError("Failed to decode a stun mesage!", ex); continue; //let this one go and for better luck next time. } StunAddress sa = new StunAddress( rawMessage.GetRemoteAddress().GetAddress(), rawMessage.GetRemoteAddress().GetPort()); sa.Local = rawMessage.GetLocalAddress(); StunMessageEvent stunMessageEvent = new StunMessageEvent(rawMessage.GetNetAccessPoint(), stunMessage, sa); messageHandler.HandleMessageEvent(stunMessageEvent); } } catch (Exception err) { //notify and bail errorHandler.HandleFatalError(this, "Unexpected Error!", err); } }
//------------------------------------ SOURCE ADDRESS -------------------------- /** * Creates a SourceFromAddressAttribute of the specified type and with * the specified address and port * @param address the address value of the address attribute * @return the newly created address attribute. */ public static SourceAddressAttribute CreateSourceAddressAttribute( StunAddress address) { SourceAddressAttribute attribute = new SourceAddressAttribute(); attribute.SetAddress(address); return(attribute); }
//------------------------------------ RESPONSE ADRESS ------------------------- /** * Creates a ResponseFromAddressAttribute of the specified type and with * the specified address and port * @param address the address value of the address attribute * @return the newly created address attribute. */ public static ResponseAddressAttribute CreateResponseAddressAttribute( StunAddress address) { ResponseAddressAttribute attribute = new ResponseAddressAttribute(); attribute.SetAddress(address); return(attribute); }
/** * Compares this object against the specified object. The result is true if * and only if the argument is not null and it represents the same address * as this object. * <p/> * Two instances of InetSocketAddress represent the same address if both the * InetAddresses (or hostnames if it is unresolved) and port numbers are * equal. * <p/> * If both addresses are unresolved, then the hostname & the port number are * compared. * @param obj the object to compare against. * @return true if the objects are the same; false otherwise. */ public override bool Equals(Object obj) { if (!(obj is StunAddress)) { return(false); } StunAddress target = (StunAddress)obj; if (target.socketAddress == null && socketAddress == null) { return(true); } return(socketAddress.Equals(target.GetSocketAddress())); }
/** * Sends the specified request through the specified access point, and * registers the specified ResponseCollector for later notification. * @param request the request to send * @param sendTo the destination address of the request. * @param sendThrough the access point to use when sending the request * @param collector the instance to notify when a response arrives or the * the transaction timeouts * @throws StunException * ILLEGAL_STATE if the stun stack is not started. <br/> * ILLEGAL_ARGUMENT if the apDescriptor references an access point that had * not been installed <br/> * NETWORK_ERROR if an error occurs while sending message bytes through the * network socket. <br/> * */ public virtual void SendRequest(Request request, StunAddress sendTo, NetAccessPointDescriptor sendThrough, ResponseCollector collector) { stunStack.CheckStarted(); StunClientTransaction clientTransaction = new StunClientTransaction(this, request, sendTo, sendThrough, collector); clientTransactions[clientTransaction.GetTransactionID()] = clientTransaction; clientTransaction.SendRequest(); }
/** * Creates a client transaction * @param providerCallback the provider that created us. * @param request the request that we are living for. * @param requestDestination the destination of the request. * @param apDescriptor the access point through which we are supposed to * @param responseCollector the instance that should receive this request's * response. * retransmit. */ public StunClientTransaction(StunProvider providerCallback, Request request, StunAddress requestDestination, NetAccessPointDescriptor apDescriptor, ResponseCollector responseCollector) { this.providerCallback = providerCallback; this.request = request; this.apDescriptor = apDescriptor; this.responseCollector = responseCollector; this.requestDestination = requestDestination; this.transactionID = TransactionID.CreateTransactionID(); request.SetTransactionID(transactionID.GetTransactionID()); runningThread = new Thread(new ThreadStart(this.Run)); }
/** * Sends the specified response message through the specified access point. * * @param transactionID the id of the transaction to use when sending the * response. Actually we are getting kind of redundant here as we already * have the id in the response object, but I am bringing out as an extra * parameter as the user might otherwise forget to explicitly set it. * @param response the message to send. * @param sendThrough the access point to use when sending the message. * @param sendTo the destination of the message. * @throws StunException TRANSACTION_DOES_NOT_EXIST if the response message * has an invalid transaction id. <br/> * ILLEGAL_STATE if the stun stack is not started. <br/> * ILLEGAL_ARGUMENT if the apDescriptor references an access point that had * not been installed <br/> * NETWORK_ERROR if an error occurs while sending message bytes through the * network socket. <br/> */ public virtual void SendResponse(byte[] transactionID, Response response, NetAccessPointDescriptor sendThrough, StunAddress sendTo) { stunStack.CheckStarted(); TransactionID tid = TransactionID.CreateTransactionID(transactionID); serverTransactions.Remove(tid); #if false throw new StunException(StunException.TRANSACTION_DOES_NOT_EXIST, "The trensaction specified in the response " + "object does not exist."); #endif response.SetTransactionID(transactionID); GetNetAccessManager().SendMessage(response, sendThrough, sendTo); }
/** * Creates and starts a new access point based on the specified socket. * If the specified access point has already been installed the method * has no effect. * * @param socket the socket that the access point should use. * @return an access point descriptor to allow further management of the * newly created access point. * @throws StunException if we fail to create or start the accesspoint. */ public NetAccessPointDescriptor InstallNetAccessPoint(MyUdpClient socket) { //no null check - let it through a null pointer exception StunAddress address = new StunAddress(socket.GetAddress().ToString(), socket.GetPort()); NetAccessPointDescriptor apDescriptor = new NetAccessPointDescriptor(address); if (netAccessPoints.ContainsKey(apDescriptor)) { return(apDescriptor); } NetAccessPoint ap = new NetAccessPoint(apDescriptor, messageQueue, this); //call the useExternalSocket method to avoid closing the socket when //removing the accesspoint. Bug Report - Dave Stuart - SipQuest ap.UseExternalSocket(socket); netAccessPoints[apDescriptor] = (ap); ap.Start(); return(apDescriptor); }
/** * Sends the specified request and blocks until a response has been * received or the request transaction has timed out. * @param request the reuqest to send * @param serverAddress the request destination address * @return the event encapsulating the response or null if no response * has been received. * @throws StunException NETWORK_ERROR or other if we fail to send * the message */ public virtual StunMessageEvent SendRequestAndWaitForResponse( Request request, StunAddress serverAddress) { Monitor.Enter(this); try { stunProvider.SendRequest(request, serverAddress, apDescriptor, this); Monitor.Wait(this); StunMessageEvent res = responseEvent; responseEvent = null; //prepare for next message return(res); } finally { Monitor.Exit(this); } }
//--------------- SENDING MESSAGES ----------------------------------------- /** * Sends the specified stun message through the specified access point. * @param stunMessage the message to send * @param apDescriptor the access point to use to send the message * @param address the destination of the message. * @throws StunException if message encoding fails, ILLEGAL_ARGUMENT if the * apDescriptor references an access point that had not been installed, * NETWORK_ERROR if an error occurs while sending message bytes through the * network socket. */ public virtual void SendMessage(Message stunMessage, NetAccessPointDescriptor apDescriptor, StunAddress address) { byte[] bytes = stunMessage.Encode(); NetAccessPoint ap = (NetAccessPoint)netAccessPoints[apDescriptor]; if(ap == null) throw new StunException( StunException.ILLEGAL_ARGUMENT, "The specified access point had not been installed."); try { ap.SendMessage(bytes, address); } catch (Exception ex) { throw new StunException(StunException.NETWORK_ERROR, "An Exception occurred while sending message bytes " +"through a network socket!", ex); } }
/** * Sends a binding request to the specified server address with only change * port flag set to true and change IP flag - to false. * @param serverAddress the address where to send the bindingRequest. * @return The returned message encapsulating event or null if no message * was received. * @throws StunException if an exception occurs while sending the messge */ private StunMessageEvent doTestIII(StunAddress serverAddress) { Request request = MessageFactory.CreateBindingRequest(); ChangeRequestAttribute changeRequest = (ChangeRequestAttribute)request.GetAttribute(Attribute.CHANGE_REQUEST); changeRequest.SetChangeIpFlag(false); changeRequest.SetChangePortFlag(true); StunMessageEvent evt = requestSender.SendRequestAndWaitForResponse(request, serverAddress); #if false if(evt != null) System.oout.println("Test III res="+evt.getRemoteAddress().toString() +" - "+ evt.getRemoteAddress().getHostName()); else Console.WriteLine("NO RESPONSE received to Test III."); #endif return evt; }
/** * Sets address to be the address transported by this attribute. * @param address that this attribute should encapsulate. */ public virtual void SetAddress(StunAddress address) { this.address = address; }
/** * Sends message through this access point's socket. * @param message the bytes to send. * @param address message destination. * @throws IOException if an exception occurs while sending the message. */ public virtual void SendMessage(byte[] message, StunAddress address) { IPEndPoint ipe = new IPEndPoint(address.GetSocketAddress().GetAddress(),address.GetSocketAddress().GetPort()); sock.Send(message, message.Length, ipe); }
/** * Creates a StunAddressDiscoverer. In order to use it one must start the * discoverer. * @param serverAddress the address of the server to interrogate. */ public SimpleAddressDetector(StunAddress serverAddress) { this.serverAddress = serverAddress; }
/** * Creates a StunAddressDiscoverer. In order to use it one must start the * discoverer. * @param localAddress the address where the stach should bind. * @param serverAddress the address of the server to interrogate. */ public NetworkConfigurationDiscoveryProcess(StunAddress localAddress, StunAddress serverAddress) { apDescriptor = new NetAccessPointDescriptor(localAddress); this.serverAddress = serverAddress; }
//------------------------------------ REFLECTED FROM -------------------------- /** * Creates a ReflectedFromAddressAttribute of the specified type and with * the specified address and port * @param address the address value of the address attribute * @return the newly created address attribute. */ public static ReflectedFromAttribute CreateReflectedFromAttribute( StunAddress address) { ReflectedFromAttribute attribute = new ReflectedFromAttribute(); attribute.SetAddress(address); return attribute; }
/** * Creates a StunAddressDiscoverer. In order to use it one must start the * discoverer. * @param apDescriptor the address where the stach should bind. * @param serverAddress the address of the server to interrogate. */ public NetworkConfigurationDiscoveryProcess(NetAccessPointDescriptor apDescriptor, StunAddress serverAddress) { this.apDescriptor = apDescriptor; this.serverAddress = serverAddress; }
/** * Sets a public address. * @param stunAddress An address that's accesible from everywhere. */ public void SetPublicAddress(StunAddress stunAddress) { this.publicAddress = stunAddress; }
/** * Implements the discovery process itself (see class description). * @return a StunDiscoveryReport containing details about the network * configuration of the host where the class is executed. * @throws StunException ILLEGAL_STATE if the discoverer has not been started * NETWORK_ERROR or ILLEGAL_ARGUMENT if a failure occurs while executing * the discovery algorithm */ virtual public StunDiscoveryReport determineAddress() { checkStarted(); StunDiscoveryReport report = new StunDiscoveryReport(); StunMessageEvent evt = doTestI(serverAddress); if (evt == null) { //UDP Blocked report.SetNatType(StunDiscoveryReport.UDP_BLOCKING_FIREWALL); return(report); } else { StunAddress mappedAddress = ((MappedAddressAttribute)evt.GetMessage(). GetAttribute(Attribute.MAPPED_ADDRESS)).GetAddress(); StunAddress backupServerAddress = ((ChangedAddressAttribute)evt.GetMessage(). GetAttribute(Attribute.CHANGED_ADDRESS)).GetAddress(); report.SetPublicAddress(mappedAddress); if (mappedAddress.Equals(apDescriptor.GetAddress())) { evt = doTestII(serverAddress); if (evt == null) { //Sym UDP Firewall report.SetNatType(StunDiscoveryReport.SYMMETRIC_UDP_FIREWALL); return(report); } else { //open internet report.SetNatType(StunDiscoveryReport.OPEN_INTERNET); return(report); } } else { evt = doTestII(serverAddress); if (evt == null) { evt = doTestI(backupServerAddress); if (evt == null) { // System.oout.println("Failed to receive a response from backup stun server!"); return(report); } StunAddress mappedAddress2 = ((MappedAddressAttribute)evt.GetMessage(). GetAttribute(Attribute.MAPPED_ADDRESS)).GetAddress(); if (mappedAddress.Equals(mappedAddress2)) { evt = doTestIII(serverAddress); if (evt == null) { //port restricted cone report.SetNatType(StunDiscoveryReport.PORT_RESTRICTED_CONE_NAT); return(report); } else { //restricted cone report.SetNatType(StunDiscoveryReport.RESTRICTED_CONE_NAT); return(report); } } else { //Symmetric NAT report.SetNatType(StunDiscoveryReport.SYMMETRIC_NAT); return(report); } } else { //full cone report.SetNatType(StunDiscoveryReport.FULL_CONE_NAT); return(report); } } } }
/** * Sends the specified request and blocks until a response has been * received or the request transaction has timed out. * @param request the reuqest to send * @param serverAddress the request destination address * @return the event encapsulating the response or null if no response * has been received. * @throws StunException NETWORK_ERROR or other if we fail to send * the message */ public virtual StunMessageEvent SendRequestAndWaitForResponse( Request request, StunAddress serverAddress) { Monitor.Enter(this); try { stunProvider.SendRequest(request, serverAddress, apDescriptor, this); Monitor.Wait(this); StunMessageEvent res = responseEvent; responseEvent = null; //prepare for next message return res; } finally { Monitor.Exit(this); } }
/** * Sends the specified response message through the specified access point. * * @param transactionID the id of the transaction to use when sending the * response. Actually we are getting kind of redundant here as we already * have the id in the response object, but I am bringing out as an extra * parameter as the user might otherwise forget to explicitly set it. * @param response the message to send. * @param sendThrough the access point to use when sending the message. * @param sendTo the destination of the message. * @throws StunException TRANSACTION_DOES_NOT_EXIST if the response message * has an invalid transaction id. <br/> * ILLEGAL_STATE if the stun stack is not started. <br/> * ILLEGAL_ARGUMENT if the apDescriptor references an access point that had * not been installed <br/> * NETWORK_ERROR if an error occurs while sending message bytes through the * network socket. <br/> */ public virtual void SendResponse(byte[] transactionID, Response response, NetAccessPointDescriptor sendThrough, StunAddress sendTo) { stunStack.CheckStarted(); TransactionID tid = TransactionID.CreateTransactionID(transactionID); serverTransactions.Remove(tid); #if false throw new StunException(StunException.TRANSACTION_DOES_NOT_EXIST, "The trensaction specified in the response " +"object does not exist."); #endif response.SetTransactionID(transactionID); GetNetAccessManager().SendMessage(response, sendThrough, sendTo); }
/** * Creates a net access point that will bind to the specified address. * * @param address a valid Stun Address. */ public NetAccessPointDescriptor(StunAddress address) { stunAddr = address; }
/** * Sends the specified request through the specified access point, and * registers the specified ResponseCollector for later notification. * @param request the request to send * @param sendTo the destination address of the request. * @param sendThrough the access point to use when sending the request * @param collector the instance to notify when a response arrives or the * the transaction timeouts * @throws StunException * ILLEGAL_STATE if the stun stack is not started. <br/> * ILLEGAL_ARGUMENT if the apDescriptor references an access point that had * not been installed <br/> * NETWORK_ERROR if an error occurs while sending message bytes through the * network socket. <br/> */ public virtual void SendRequest( Request request, StunAddress sendTo, NetAccessPointDescriptor sendThrough, ResponseCollector collector ) { stunStack.CheckStarted(); StunClientTransaction clientTransaction = new StunClientTransaction(this, request, sendTo, sendThrough, collector); clientTransactions[clientTransaction.GetTransactionID()] = clientTransaction; clientTransaction.SendRequest(); }
/** * Creates a BindingResponse assigning the specified values to mandatory * headers. * * @param mappedAddress the address to assign the mappedAddressAttribute * @param sourceAddress the address to assign the sourceAddressAttribute * @param changedAddress the address to assign the changedAddressAttribute * @return a BindingResponse assigning the specified values to mandatory * headers. * @throws StunException ILLEGAL_ARGUMENT */ public static Response CreateBindingResponse(StunAddress mappedAddress, StunAddress sourceAddress, StunAddress changedAddress) { Response bindingResponse = new Response(); bindingResponse.SetMessageType(Message.BINDING_RESPONSE); //mapped address MappedAddressAttribute mappedAddressAttribute = AttributeFactory.CreateMappedAddressAttribute(mappedAddress); //source address SourceAddressAttribute sourceAddressAttribute = AttributeFactory.CreateSourceAddressAttribute(sourceAddress); //changed address ChangedAddressAttribute changedAddressAttribute = AttributeFactory.CreateChangedAddressAttribute(changedAddress); bindingResponse.AddAttribute(mappedAddressAttribute); bindingResponse.AddAttribute(sourceAddressAttribute); bindingResponse.AddAttribute(changedAddressAttribute); return bindingResponse; }
//------------------------------------ CHANGED ADDRESS ------------------------- /** * Creates a changedAddressAttribute of the specified type and with the * specified address and port * @param address the address value of the address attribute * @return the newly created address attribute. */ public static ChangedAddressAttribute CreateChangedAddressAttribute(StunAddress address) { ChangedAddressAttribute attribute= new ChangedAddressAttribute(); attribute.SetAddress(address); return attribute; }
//------------------------------------ MAPPED ADDRESS -------------------------- /** * Creates a MappedAddressAttribute of the specified type and with the * specified address and port * @param address the address value of the address attribute * @return the newly created address attribute. */ public static MappedAddressAttribute CreateMappedAddressAttribute( StunAddress address) { MappedAddressAttribute attribute = new MappedAddressAttribute(); attribute.SetAddress(address); return attribute; }
//------------------------------------ SOURCE ADDRESS -------------------------- /** * Creates a SourceFromAddressAttribute of the specified type and with * the specified address and port * @param address the address value of the address attribute * @return the newly created address attribute. */ public static SourceAddressAttribute CreateSourceAddressAttribute( StunAddress address) { SourceAddressAttribute attribute = new SourceAddressAttribute(); attribute.SetAddress(address); return attribute; }
/** * Does the message parsing. */ public virtual void Run() { //add an extra try/catch block that handles uncatched errors and helps avoid //having dead threads in our pools. try { while (isRunning) { RawMessage rawMessage = null; rawMessage = messageQueue.Remove(); // were we asked to stop? if (!IsRunning()) return; //anything to parse? if (rawMessage == null) continue; Message stunMessage = null; try { stunMessage = Message.Decode(rawMessage.GetBytes(), 0, rawMessage.GetMessageLength()); } catch (StunException ex) { errorHandler.HandleError("Failed to decode a stun mesage!", ex); continue; //let this one go and for better luck next time. } StunAddress sa = new StunAddress( rawMessage.GetRemoteAddress().GetAddress(), rawMessage.GetRemoteAddress().GetPort() ); sa.Local = rawMessage.GetLocalAddress(); StunMessageEvent stunMessageEvent = new StunMessageEvent(rawMessage.GetNetAccessPoint(), stunMessage, sa); messageHandler.HandleMessageEvent(stunMessageEvent); } } catch(Exception err) { //notify and bail errorHandler.HandleFatalError(this, "Unexpected Error!", err); } }
//------------------------------------ RESPONSE ADRESS ------------------------- /** * Creates a ResponseFromAddressAttribute of the specified type and with * the specified address and port * @param address the address value of the address attribute * @return the newly created address attribute. */ public static ResponseAddressAttribute CreateResponseAddressAttribute( StunAddress address) { ResponseAddressAttribute attribute = new ResponseAddressAttribute(); attribute.SetAddress(address); return attribute; }
/** * Sends message through this access point's socket. * @param message the bytes to send. * @param address message destination. * @throws IOException if an exception occurs while sending the message. */ public virtual void SendMessage(byte[] message, StunAddress address) { IPEndPoint ipe = new IPEndPoint(address.GetSocketAddress().GetAddress(), address.GetSocketAddress().GetPort()); sock.Send(message, message.Length, ipe); }
/** * Creates and starts a new access point based on the specified socket. * If the specified access point has already been installed the method * has no effect. * * @param socket the socket that the access point should use. * @return an access point descriptor to allow further management of the * newly created access point. * @throws StunException if we fail to create or start the accesspoint. */ public NetAccessPointDescriptor InstallNetAccessPoint(MyUdpClient socket) { //no null check - let it through a null pointer exception StunAddress address = new StunAddress(socket.GetAddress().ToString(), socket.GetPort()); NetAccessPointDescriptor apDescriptor = new NetAccessPointDescriptor(address); if(netAccessPoints.ContainsKey(apDescriptor)) return apDescriptor; NetAccessPoint ap = new NetAccessPoint(apDescriptor, messageQueue, this); //call the useExternalSocket method to avoid closing the socket when //removing the accesspoint. Bug Report - Dave Stuart - SipQuest ap.UseExternalSocket(socket); netAccessPoints[apDescriptor] = (ap); ap.Start(); return apDescriptor; }
//---------- main /** * Runs the discoverer and shows a message dialog with the returned report. * @param args args[0] - stun server address, args[1] - port. in the case of * no args - defaults are provided. * @throws java.lang.Exception if an exception occurrs during the discovery * process. */ public static void main(String[] args) { StunAddress localAddr = null; StunAddress serverAddr = null; if(args.Length == 4) { localAddr = new StunAddress(args[2], Integer.valueOf(args[3]).intValue()); serverAddr = new StunAddress(args[0], Integer.valueOf(args[1]).intValue()); } else { localAddr = new StunAddress(InetAddress.getLocalHost(), 5678); serverAddr = new StunAddress("stun01bak.sipphone.com.", 3479); } NetworkConfigurationDiscoveryProcess addressDiscovery = new NetworkConfigurationDiscoveryProcess(localAddr, serverAddr); addressDiscovery.start(); StunDiscoveryReport report = addressDiscovery.determineAddress(); System.oout.println(report); // javax.swing.JOptionPane.showMessageDialog( // null, // report.toString(), // "Stun Discovery Process", // javax.swing.JOptionPane.INFORMATION_MESSAGE); System.exit(0); }