├── .gitignore ├── LICENSE ├── README.md ├── lib └── log │ ├── LICENSE.txt │ ├── NOTICE.txt │ └── RELEASE-NOTES.txt └── src ├── META-INF └── MANIFEST.MF ├── com └── hankcs │ └── network │ ├── IceClient.java │ ├── Peer.java │ └── SdpUtils.java └── log4j2.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | IceNAT 2 | ====== 3 | 4 | Demonstrate how to do hole punching with rfc5766-turn-server and ice4j. 5 | -------------------------------------------------------------------------------- /lib/log/LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 1999-2005 The Apache Software Foundation 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /lib/log/NOTICE.txt: -------------------------------------------------------------------------------- 1 | Apache Log4j 2 | Copyright 1999-2014 Apache Software Foundation 3 | 4 | This product includes software developed at 5 | The Apache Software Foundation (http://www.apache.org/). 6 | 7 | ResolverUtil.java 8 | Copyright 2005-2006 Tim Fennell 9 | 10 | Dumbster SMTP test server 11 | Copyright 2004 Jason Paul Kitchen 12 | -------------------------------------------------------------------------------- /lib/log/RELEASE-NOTES.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache Log4j 2.0.2 RELEASE NOTES 3 | 4 | The Apache Log4j 2 team is pleased to announce the Log4j 2.0.2 release! 5 | 6 | Apache log4j is a well known framework for logging application behavior. Log4j 2 is an upgrade to 7 | Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides 8 | many of the improvements available in Logback while fixing some inherent problems in Logback's 9 | architecture. 10 | 11 | This is the third GA release which contains several bugfixes from the previous release. 12 | 13 | Bug fixes and enhancements 14 | 15 | Changes in this version include: 16 | 17 | 18 | Fixed Bugs: 19 | o LOG4J2-773: Site: log4j-core component pages were still using the old logo. 20 | o LOG4J2-760: Documentation improvement: link to dependency tree from log4j-core component page, 21 | link to log4j-core component page from FAQ page. 22 | o LOG4J2-679: Resolved race condition that caused log file rotation to fail with error: "Unable to create directory ..." 23 | o LOG4J2-726: Prevent application from hanging when PatternLayout configuration has opening '{' but no closing '}'. 24 | o LOG4J2-769: Startup takes a long time if you have empty packages attribute. Thanks to Scott Harrington. 25 | o LOG4J2-763: Improved asynchronous loggers and appenders to ensure the formatted message does not change even if 26 | parameters are modified by the application. (ParameterizedMessage was already safe.) 27 | Improved documentation. Thanks to Stephen Connolly. 28 | o LOG4J2-729: Emit warning message to console if no configuration file found. 29 | o LOG4J2-765: Improve warning message when missing log4j-core in the classpath. 30 | o LOG4J2-722: Clarified in documentation that Commons Logging jar is required when using log4j-jcl. 31 | o LOG4J2-723: Clarified in documentation that SLF4J API jar is required when using log4j-slf4j-impl. 32 | o LOG4J2-759: Fixed various minor site/documentation issues, mostly versioning related. 33 | o LOG4J2-756: Prevent JUnit test from creating unnecessary Log4j2Plugins.dat during build. Thanks to Scott Harrington. 34 | 35 | Changes: 36 | o LOG4J2-775: Update Apache Flume to 1.5.0.1 from 1.5.0. 37 | o LOG4J2-730: Allow Log4jContextFactory subclasses to specify a custom ContextSelector. 38 | 39 | 40 | Apache Log4j 2.0.2 requires a minimum of Java 6 to build and run. Basic compatibility with 41 | Log4j 1.x is provided through the log4j-1.2-api component, however it does not implement some of the 42 | very implementation specific classes and methods. The package names and Maven groupId have been changed to 43 | org.apache.logging.log4j to avoid any conflicts with log4j 1.x. 44 | 45 | For complete information on Apache Log4j 2, including instructions on how to submit bug reports, 46 | patches, or suggestions for improvement, see the Apache Apache Log4j 2 website: 47 | 48 | http://logging.apache.org/log4j/2.x/ 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: com.hankcs.network.Peer 3 | 4 | -------------------------------------------------------------------------------- /src/com/hankcs/network/IceClient.java: -------------------------------------------------------------------------------- 1 | package com.hankcs.network; 2 | 3 | import java.beans.PropertyChangeEvent; 4 | import java.beans.PropertyChangeListener; 5 | import java.io.BufferedReader; 6 | import java.io.InputStreamReader; 7 | import java.net.DatagramSocket; 8 | import java.net.SocketAddress; 9 | import java.util.List; 10 | 11 | import org.apache.commons.lang3.StringUtils; 12 | import org.apache.log4j.Logger; 13 | import org.ice4j.Transport; 14 | import org.ice4j.TransportAddress; 15 | import org.ice4j.ice.Agent; 16 | import org.ice4j.ice.Component; 17 | import org.ice4j.ice.IceMediaStream; 18 | import org.ice4j.ice.IceProcessingState; 19 | import org.ice4j.ice.LocalCandidate; 20 | import org.ice4j.ice.NominationStrategy; 21 | import org.ice4j.ice.RemoteCandidate; 22 | import org.ice4j.ice.harvest.StunCandidateHarvester; 23 | import org.ice4j.ice.harvest.TurnCandidateHarvester; 24 | import org.ice4j.security.LongTermCredential; 25 | 26 | public class IceClient 27 | { 28 | 29 | private int port; 30 | 31 | private String streamName; 32 | 33 | private Agent agent; 34 | 35 | private String localSdp; 36 | 37 | private String remoteSdp; 38 | 39 | private String[] turnServers = new String[]{"180.160.188.246:3478"}; 40 | 41 | private String[] stunServers = new String[]{"180.160.188.246:3478"}; 42 | 43 | private String username = "u1"; 44 | 45 | private String password = "p1"; 46 | 47 | private IceProcessingListener listener; 48 | 49 | static Logger log = Logger.getLogger(IceClient.class); 50 | 51 | public IceClient(int port, String streamName) 52 | { 53 | this.port = port; 54 | this.streamName = streamName; 55 | this.listener = new IceProcessingListener(); 56 | } 57 | 58 | public void init() throws Throwable 59 | { 60 | 61 | agent = createAgent(port, streamName); 62 | 63 | agent.setNominationStrategy(NominationStrategy.NOMINATE_HIGHEST_PRIO); 64 | 65 | agent.addStateChangeListener(listener); 66 | 67 | agent.setControlling(false); 68 | 69 | agent.setTa(10000); 70 | 71 | localSdp = SdpUtils.createSDPDescription(agent); 72 | 73 | log.info("=================== feed the following" 74 | + " to the remote agent ==================="); 75 | 76 | System.out.println(localSdp); 77 | 78 | log.info("======================================" 79 | + "========================================\n"); 80 | } 81 | 82 | public DatagramSocket getDatagramSocket() throws Throwable 83 | { 84 | 85 | LocalCandidate localCandidate = agent 86 | .getSelectedLocalCandidate(streamName); 87 | 88 | IceMediaStream stream = agent.getStream(streamName); 89 | List components = stream.getComponents(); 90 | for (Component c : components) 91 | { 92 | log.info(c); 93 | } 94 | log.info(localCandidate.toString()); 95 | LocalCandidate candidate = (LocalCandidate) localCandidate; 96 | return candidate.getDatagramSocket(); 97 | 98 | } 99 | 100 | public SocketAddress getRemotePeerSocketAddress() 101 | { 102 | RemoteCandidate remoteCandidate = agent 103 | .getSelectedRemoteCandidate(streamName); 104 | log.info("Remote candinate transport address:" 105 | + remoteCandidate.getTransportAddress()); 106 | log.info("Remote candinate host address:" 107 | + remoteCandidate.getHostAddress()); 108 | log.info("Remote candinate mapped address:" 109 | + remoteCandidate.getMappedAddress()); 110 | log.info("Remote candinate relayed address:" 111 | + remoteCandidate.getRelayedAddress()); 112 | log.info("Remote candinate reflexive address:" 113 | + remoteCandidate.getReflexiveAddress()); 114 | return remoteCandidate.getTransportAddress(); 115 | } 116 | 117 | /** 118 | * Reads an SDP description from the standard input.In production 119 | * environment that we can exchange SDP with peer through signaling 120 | * server(SIP server) 121 | */ 122 | public void exchangeSdpWithPeer() throws Throwable 123 | { 124 | log.info("Paste remote SDP here. Enter an empty line to proceed:"); 125 | BufferedReader reader = new BufferedReader(new InputStreamReader( 126 | System.in)); 127 | 128 | StringBuilder buff = new StringBuilder(); 129 | String line = new String(); 130 | 131 | while ((line = reader.readLine()) != null) 132 | { 133 | line = line.trim(); 134 | if (line.length() == 0) 135 | { 136 | break; 137 | } 138 | buff.append(line); 139 | buff.append("\r\n"); 140 | } 141 | 142 | remoteSdp = buff.toString(); 143 | 144 | SdpUtils.parseSDP(agent, remoteSdp); 145 | } 146 | 147 | public void startConnect() throws InterruptedException 148 | { 149 | 150 | if (StringUtils.isBlank(remoteSdp)) 151 | { 152 | throw new NullPointerException( 153 | "Please exchange sdp information with peer before start connect! "); 154 | } 155 | 156 | agent.startConnectivityEstablishment(); 157 | 158 | // agent.runInStunKeepAliveThread(); 159 | 160 | synchronized (listener) 161 | { 162 | listener.wait(); 163 | } 164 | 165 | } 166 | 167 | private Agent createAgent(int rtpPort, String streamName) throws Throwable 168 | { 169 | return createAgent(rtpPort, streamName, false); 170 | } 171 | 172 | private Agent createAgent(int rtpPort, String streamName, 173 | boolean isTrickling) throws Throwable 174 | { 175 | 176 | long startTime = System.currentTimeMillis(); 177 | 178 | Agent agent = new Agent(); 179 | 180 | agent.setTrickling(isTrickling); 181 | 182 | // STUN 183 | for (String server : stunServers) 184 | { 185 | String[] pair = server.split(":"); 186 | agent.addCandidateHarvester(new StunCandidateHarvester( 187 | new TransportAddress(pair[0], Integer.parseInt(pair[1]), 188 | Transport.UDP))); 189 | } 190 | 191 | // TURN 192 | LongTermCredential longTermCredential = new LongTermCredential(username, 193 | password); 194 | 195 | for (String server : turnServers) 196 | { 197 | String[] pair = server.split(":"); 198 | agent.addCandidateHarvester(new TurnCandidateHarvester( 199 | new TransportAddress(pair[0], Integer.parseInt(pair[1]), Transport.UDP), 200 | longTermCredential)); 201 | } 202 | // STREAMS 203 | createStream(rtpPort, streamName, agent); 204 | 205 | long endTime = System.currentTimeMillis(); 206 | long total = endTime - startTime; 207 | 208 | log.info("Total harvesting time: " + total + "ms."); 209 | 210 | return agent; 211 | } 212 | 213 | private IceMediaStream createStream(int rtpPort, String streamName, 214 | Agent agent) throws Throwable 215 | { 216 | long startTime = System.currentTimeMillis(); 217 | IceMediaStream stream = agent.createMediaStream(streamName); 218 | // rtp 219 | Component component = agent.createComponent(stream, Transport.UDP, 220 | rtpPort, rtpPort, rtpPort + 100); 221 | 222 | long endTime = System.currentTimeMillis(); 223 | log.info("Component Name:" + component.getName()); 224 | log.info("RTP Component created in " + (endTime - startTime) + " ms"); 225 | 226 | return stream; 227 | } 228 | 229 | /** 230 | * Receive notify event when ice processing state has changed. 231 | */ 232 | public static final class IceProcessingListener implements 233 | PropertyChangeListener 234 | { 235 | 236 | private long startTime = System.currentTimeMillis(); 237 | 238 | public void propertyChange(PropertyChangeEvent event) 239 | { 240 | 241 | Object state = event.getNewValue(); 242 | 243 | log.info("Agent entered the " + state + " state."); 244 | if (state == IceProcessingState.COMPLETED) 245 | { 246 | long processingEndTime = System.currentTimeMillis(); 247 | log.info("Total ICE processing time: " 248 | + (processingEndTime - startTime) + "ms"); 249 | Agent agent = (Agent) event.getSource(); 250 | List streams = agent.getStreams(); 251 | 252 | for (IceMediaStream stream : streams) 253 | { 254 | log.info("Stream name: " + stream.getName()); 255 | List components = stream.getComponents(); 256 | for (Component c : components) 257 | { 258 | log.info("------------------------------------------"); 259 | log.info("Component of stream:" + c.getName() 260 | + ",selected of pair:" + c.getSelectedPair()); 261 | log.info("------------------------------------------"); 262 | } 263 | } 264 | 265 | log.info("Printing the completed check lists:"); 266 | for (IceMediaStream stream : streams) 267 | { 268 | 269 | log.info("Check list for stream: " + stream.getName()); 270 | 271 | log.info("nominated check list:" + stream.getCheckList()); 272 | } 273 | synchronized (this) 274 | { 275 | this.notifyAll(); 276 | } 277 | } 278 | else if (state == IceProcessingState.TERMINATED) 279 | { 280 | log.info("ice processing TERMINATED"); 281 | } 282 | else if (state == IceProcessingState.FAILED) 283 | { 284 | log.info("ice processing FAILED"); 285 | ((Agent) event.getSource()).free(); 286 | } 287 | } 288 | } 289 | 290 | public String[] getTurnServers() 291 | { 292 | return turnServers; 293 | } 294 | 295 | public void setTurnServers(String[] turnServers) 296 | { 297 | this.turnServers = turnServers; 298 | } 299 | 300 | public String[] getStunServers() 301 | { 302 | return stunServers; 303 | } 304 | 305 | public void setStunServers(String[] stunServers) 306 | { 307 | this.stunServers = stunServers; 308 | } 309 | 310 | public String getUsername() 311 | { 312 | return username; 313 | } 314 | 315 | public void setUsername(String username) 316 | { 317 | this.username = username; 318 | } 319 | 320 | public String getPassword() 321 | { 322 | return password; 323 | } 324 | 325 | public void setPassword(String password) 326 | { 327 | this.password = password; 328 | } 329 | } -------------------------------------------------------------------------------- /src/com/hankcs/network/Peer.java: -------------------------------------------------------------------------------- 1 | package com.hankcs.network; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.net.DatagramPacket; 7 | import java.net.DatagramSocket; 8 | import java.net.SocketAddress; 9 | 10 | 11 | public class Peer 12 | { 13 | public static void main(String[] args) throws Throwable 14 | { 15 | try 16 | { 17 | IceClient client = new IceClient(8888, "text"); 18 | client.init(); 19 | client.exchangeSdpWithPeer(); 20 | client.startConnect(); 21 | final DatagramSocket socket = client.getDatagramSocket(); 22 | final SocketAddress remoteAddress = client 23 | .getRemotePeerSocketAddress(); 24 | System.out.println(socket.toString()); 25 | new Thread(new Runnable() 26 | { 27 | 28 | public void run() 29 | { 30 | while (true) 31 | { 32 | try 33 | { 34 | byte[] buf = new byte[1024]; 35 | DatagramPacket packet = new DatagramPacket(buf, 36 | buf.length); 37 | socket.receive(packet); 38 | System.out.println(packet.getAddress() + ":" + packet.getPort() + " says: " + new String(packet.getData(), 0, packet.getLength())); 39 | } 40 | catch (IOException e) 41 | { 42 | e.printStackTrace(); 43 | } 44 | } 45 | } 46 | }).start(); 47 | 48 | new Thread(new Runnable() 49 | { 50 | 51 | public void run() 52 | { 53 | try 54 | { 55 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 56 | String line; 57 | // 从键盘读取 58 | while ((line = reader.readLine()) != null) 59 | { 60 | line = line.trim(); 61 | if (line.length() == 0) 62 | { 63 | break; 64 | } 65 | byte[] buf = (line).getBytes(); 66 | DatagramPacket packet = new DatagramPacket(buf, buf.length); 67 | packet.setSocketAddress(remoteAddress); 68 | socket.send(packet); 69 | } 70 | } 71 | catch (Exception e) 72 | { 73 | e.printStackTrace(); 74 | } 75 | 76 | } 77 | }).start(); 78 | } 79 | catch (Exception e) 80 | { 81 | e.printStackTrace(); 82 | } 83 | 84 | } 85 | 86 | } -------------------------------------------------------------------------------- /src/com/hankcs/network/SdpUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. 3 | * Maintained by the Jitsi community (https://jitsi.org). 4 | * 5 | * Distributable under LGPL license. See terms of license at gnu.org. 6 | */ 7 | package com.hankcs.network; 8 | 9 | import org.ice4j.Transport; 10 | import org.ice4j.TransportAddress; 11 | import org.ice4j.ice.*; 12 | import org.ice4j.ice.sdp.CandidateAttribute; 13 | import org.ice4j.ice.sdp.IceSdpUtils; 14 | 15 | import javax.sdp.*; 16 | import java.util.StringTokenizer; 17 | import java.util.Vector; 18 | 19 | /** 20 | * Utilities for manipulating SDP. Some of the utilities in this method do 21 | * not try to act smart and make a lot of assumptions (e.g. at least one 22 | * media stream with at least one component) that may not always be true in real 23 | * life and lead to exceptions. Therefore, make sure you reread the code if 24 | * reusing it in an application. It should be fine for the purposes of our ice4j 25 | * examples though. 26 | * 27 | * @author Emil Ivov 28 | */ 29 | public class SdpUtils 30 | { 31 | /** 32 | * Creates a session description containing the streams from the specified 33 | * agent using dummy codecs. This method is unlikely to be of use 34 | * to integrating applications as they would likely just want to feed a 35 | * {@link javax.sdp.MediaDescription} and have it populated with all the necessary 36 | * attributes. 37 | * 38 | * @param agent the {@link org.ice4j.ice.Agent} we'd like to generate. 39 | * 40 | * @return a {@link SessionDescription} representing agent's 41 | * streams. 42 | * 43 | * @throws Throwable on rainy days 44 | */ 45 | public static String createSDPDescription(Agent agent) throws Throwable 46 | { 47 | SdpFactory factory = SdpFactory.getInstance(); 48 | SessionDescription sdess = factory.createSessionDescription(); 49 | 50 | IceSdpUtils.initSessionDescription(sdess, agent); 51 | 52 | return sdess.toString(); 53 | } 54 | 55 | /** 56 | * Configures localAgent the the remote peer streams, components, 57 | * and candidates specified in sdp 58 | * 59 | * @param localAgent the {@link org.ice4j.ice.Agent} that we'd like to configure. 60 | * 61 | * @param sdp the SDP string that the remote peer sent. 62 | * 63 | * @throws Exception for all sorts of reasons. 64 | */ 65 | @SuppressWarnings("unchecked") // jain-sdp legacy code. 66 | public static void parseSDP(Agent localAgent, String sdp) 67 | throws Exception 68 | { 69 | SdpFactory factory = SdpFactory.getInstance(); 70 | SessionDescription sdess = factory.createSessionDescription(sdp); 71 | 72 | for(IceMediaStream stream : localAgent.getStreams()) 73 | { 74 | stream.setRemotePassword(sdess.getAttribute("ice-pwd")); 75 | stream.setRemoteUfrag(sdess.getAttribute("ice-ufrag")); 76 | } 77 | 78 | Connection globalConn = sdess.getConnection(); 79 | String globalConnAddr = null; 80 | if(globalConn != null) 81 | globalConnAddr = globalConn.getAddress(); 82 | 83 | Vector mdescs = sdess.getMediaDescriptions(true); 84 | 85 | for (MediaDescription desc : mdescs) 86 | { 87 | String streamName = desc.getMedia().getMediaType(); 88 | 89 | IceMediaStream stream = localAgent.getStream(streamName); 90 | 91 | if(stream == null) 92 | continue; 93 | 94 | Vector attributes = desc.getAttributes(true); 95 | for( Attribute attribute : attributes) 96 | { 97 | if(!attribute.getName().equals(CandidateAttribute.NAME)) 98 | continue; 99 | 100 | parseCandidate(attribute, stream); 101 | } 102 | 103 | //set default candidates 104 | Connection streamConn = desc.getConnection(); 105 | String streamConnAddr = null; 106 | if(streamConn != null) 107 | streamConnAddr = streamConn.getAddress(); 108 | else 109 | streamConnAddr = globalConnAddr; 110 | 111 | int port = desc.getMedia().getMediaPort(); 112 | 113 | TransportAddress defaultRtpAddress = 114 | new TransportAddress(streamConnAddr, port, Transport.UDP); 115 | 116 | int rtcpPort = port + 1; 117 | String rtcpAttributeValue = desc.getAttribute("rtcp"); 118 | 119 | if (rtcpAttributeValue != null) 120 | rtcpPort = Integer.parseInt(rtcpAttributeValue); 121 | 122 | TransportAddress defaultRtcpAddress = 123 | new TransportAddress(streamConnAddr, rtcpPort, Transport.UDP); 124 | 125 | Component rtpComponent = stream.getComponent(Component.RTP); 126 | Component rtcpComponent = stream.getComponent(Component.RTCP); 127 | 128 | Candidate defaultRtpCandidate 129 | = rtpComponent.findRemoteCandidate(defaultRtpAddress); 130 | rtpComponent.setDefaultRemoteCandidate(defaultRtpCandidate); 131 | 132 | if(rtcpComponent != null) 133 | { 134 | Candidate defaultRtcpCandidate 135 | = rtcpComponent.findRemoteCandidate(defaultRtcpAddress); 136 | rtcpComponent.setDefaultRemoteCandidate(defaultRtcpCandidate); 137 | } 138 | } 139 | } 140 | 141 | /** 142 | * Parses the attribute. 143 | * 144 | * @param attribute the attribute that we need to parse. 145 | * @param stream the {@link org.ice4j.ice.IceMediaStream} that the candidate is supposed 146 | * to belong to. 147 | * 148 | * @return a newly created {@link org.ice4j.ice.RemoteCandidate} matching the 149 | * content of the specified attribute or null if the 150 | * candidate belonged to a component we don't have. 151 | */ 152 | private static RemoteCandidate parseCandidate(Attribute attribute, 153 | IceMediaStream stream) 154 | { 155 | String value = null; 156 | 157 | try{ 158 | value = attribute.getValue(); 159 | }catch (Throwable t){}//can't happen 160 | 161 | StringTokenizer tokenizer = new StringTokenizer(value); 162 | 163 | //XXX add exception handling. 164 | String foundation = tokenizer.nextToken(); 165 | int componentID = Integer.parseInt( tokenizer.nextToken() ); 166 | Transport transport = Transport.parse(tokenizer.nextToken()); 167 | long priority = Long.parseLong(tokenizer.nextToken()); 168 | String address = tokenizer.nextToken(); 169 | int port = Integer.parseInt(tokenizer.nextToken()); 170 | 171 | TransportAddress transAddr 172 | = new TransportAddress(address, port, transport); 173 | 174 | tokenizer.nextToken(); //skip the "typ" String 175 | CandidateType type = CandidateType.parse(tokenizer.nextToken()); 176 | 177 | Component component = stream.getComponent(componentID); 178 | 179 | if(component == null) 180 | return null; 181 | 182 | // check if there's a related address property 183 | 184 | RemoteCandidate relatedCandidate = null; 185 | if (tokenizer.countTokens() >= 4) 186 | { 187 | tokenizer.nextToken(); // skip the raddr element 188 | String relatedAddr = tokenizer.nextToken(); 189 | tokenizer.nextToken(); // skip the rport element 190 | int relatedPort = Integer.parseInt(tokenizer.nextToken()); 191 | 192 | TransportAddress raddr = new TransportAddress( 193 | relatedAddr, relatedPort, Transport.UDP); 194 | 195 | relatedCandidate = component.findRemoteCandidate(raddr); 196 | } 197 | 198 | RemoteCandidate cand = new RemoteCandidate(transAddr, component, type, 199 | foundation, priority, relatedCandidate); 200 | 201 | component.addRemoteCandidate(cand); 202 | 203 | return cand; 204 | } 205 | 206 | 207 | } 208 | -------------------------------------------------------------------------------- /src/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | --------------------------------------------------------------------------------