├── .github └── workflows │ └── main.yml ├── .gitignore ├── Dockerfile ├── LICENSE-2.0.txt ├── Makefile ├── README.md ├── go.mod ├── go.sum ├── main.go ├── main_test.go ├── tcp └── tcp.go └── udp └── udp.go /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | # Based on: 2 | # https://www.prestonlamb.com/blog/creating-a-docker-image-with-github-actions 3 | # https://www.learncloudnative.com/blog/2020-02-20-github-action-build-push-docker-images 4 | 5 | on: 6 | push: 7 | branches: 8 | - master 9 | 10 | jobs: 11 | push: 12 | runs-on: ubuntu-latest 13 | env: 14 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v2 18 | with: 19 | fetch-depth: 0 20 | 21 | - name: Create Release 22 | id: release 23 | uses: rymndhng/release-on-push-action@v0.27.0 24 | with: 25 | bump_version_scheme: minor 26 | 27 | - name: Check Output Parameters 28 | run: | 29 | echo "Got tag name ${{ steps.release.outputs.tag_name }}" 30 | echo "Got release version ${{ steps.release.outputs.version }}" 31 | 32 | - name: Log into registry 33 | run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login ${{ secrets.DOCKER_REGISTRY_URL }} -u ${{ secrets.DOCKER_USERNAME }} --password-stdin 34 | 35 | - name: Build and push image 36 | run: make push version=${{ steps.release.outputs.version }} 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # IDEA project settings 2 | .idea 3 | *.ipr 4 | *.iws 5 | *.iml 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.18.7 as builder 2 | WORKDIR /go/src/github.com/dddpaul/gonc 3 | ADD . ./ 4 | RUN make build-alpine 5 | 6 | FROM alpine:latest 7 | WORKDIR /app 8 | COPY --from=builder /go/src/github.com/dddpaul/gonc/bin/gonc . 9 | 10 | ENTRYPOINT ["./gonc"] 11 | -------------------------------------------------------------------------------- /LICENSE-2.0.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 [yyyy] [name of copyright owner] 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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all build release 2 | 3 | IMAGE=dddpaul/gonc 4 | 5 | all: build 6 | 7 | build-alpine: 8 | CGO_ENABLED=0 GOOS=linux go test 9 | CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o ./bin/gonc ./main.go 10 | 11 | build: 12 | @docker build --tag=${IMAGE} . 13 | 14 | debug: 15 | @docker run -it --entrypoint=sh ${IMAGE} 16 | 17 | release: build 18 | @echo "Tag image with version $(version)" 19 | @docker tag ${IMAGE} ${IMAGE}:$(version) 20 | 21 | push: release 22 | @docker push ${IMAGE} 23 | @docker push ${IMAGE}:$(version) 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | gonc 2 | ========= 3 | 4 | Simple Netcat tool written in Go. 5 | 6 | Install: 7 | 8 | ``` 9 | go get -u github.com/dddpaul/gonc 10 | ``` 11 | 12 | Usage: 13 | 14 | ``` 15 | gonc [OPTIONS] 16 | -host="": Remote host to connect, i.e. 127.0.0.1 17 | -listen=false: Listen mode 18 | -port="": Port to listen on or connect to (prepended by colon), i.e. :9999 19 | -proto="tcp": TCP/UDP mode 20 | ``` 21 | 22 | Comments: 23 | 24 | * Send `~.` to disconnect in UDP mode. 25 | 26 | You can grab some binaries from [Bintray](http://dl.bintray.com/dddpaul/generic/gonc/). This is a simplest way to get Netcat for Windows :) 27 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/dddpaul/gonc 2 | 3 | go 1.18 4 | 5 | require github.com/stretchr/testify v1.8.1 6 | 7 | require ( 8 | github.com/davecgh/go-spew v1.1.1 // indirect 9 | github.com/pmezard/go-difflib v1.0.0 // indirect 10 | gopkg.in/yaml.v3 v3.0.1 // indirect 11 | ) 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 5 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 6 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 7 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 8 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 9 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 10 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 11 | github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= 12 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 13 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 14 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 15 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 16 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 17 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 18 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | 6 | "github.com/dddpaul/gonc/tcp" 7 | "github.com/dddpaul/gonc/udp" 8 | ) 9 | 10 | func main() { 11 | var host, port, proto string 12 | var listen bool 13 | flag.StringVar(&host, "host", "", "Remote host to connect, i.e. 127.0.0.1") 14 | flag.StringVar(&proto, "proto", "tcp", "TCP/UDP mode") 15 | flag.BoolVar(&listen, "listen", false, "Listen mode") 16 | flag.StringVar(&port, "port", ":9999", "Port to listen on or connect to (prepended by colon), i.e. :9999") 17 | flag.Parse() 18 | 19 | switch proto { 20 | case "tcp": 21 | if listen { 22 | tcp.StartServer(proto, port) 23 | } else if host != "" { 24 | tcp.StartClient(proto, host, port) 25 | } else { 26 | flag.Usage() 27 | } 28 | case "udp": 29 | if listen { 30 | udp.StartServer(proto, port) 31 | } else if host != "" { 32 | udp.StartClient(proto, host, port) 33 | } else { 34 | flag.Usage() 35 | } 36 | default: 37 | flag.Usage() 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "net" 6 | "testing" 7 | 8 | "github.com/dddpaul/gonc/tcp" 9 | "github.com/dddpaul/gonc/udp" 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | var Host = "127.0.0.1" 14 | var Port = ":9991" 15 | var Input = "Input from my side, пока, £, 语汉" 16 | var InputFromOtherSide = "Input from other side, пока, £, 语汉, 123" 17 | 18 | func TestTransferStreams(t *testing.T) { 19 | in := bytes.NewReader([]byte(Input)) 20 | out := new(bytes.Buffer) 21 | 22 | ready := make(chan bool, 1) 23 | done := make(chan bool, 1) 24 | 25 | // Send data from "my" side 26 | go func() { 27 | <-ready 28 | con, err := net.Dial("tcp", Host+Port) 29 | assert.Nil(t, err) 30 | tcp.TransferStreams(con, in, out) 31 | done <- true 32 | }() 33 | 34 | // Start server on the "other" side 35 | ln, err := net.Listen("tcp", Port) 36 | assert.Nil(t, err) 37 | ready <- true 38 | con, err := ln.Accept() 39 | assert.Nil(t, err) 40 | 41 | // Read data on the "other" side 42 | buf := make([]byte, 1024) 43 | n, err := con.Read(buf) 44 | assert.Nil(t, err) 45 | assert.Equal(t, Input, string(buf[0:n])) 46 | 47 | // Send data from the "other" side 48 | n, err = con.Write([]byte(InputFromOtherSide)) 49 | assert.Nil(t, err) 50 | err = con.Close() 51 | assert.Nil(t, err) 52 | <-done 53 | assert.Equal(t, InputFromOtherSide, string(out.Bytes()[0:n])) 54 | } 55 | 56 | func TestTransferPackets(t *testing.T) { 57 | in := bytes.NewReader([]byte(Input)) 58 | out := new(bytes.Buffer) 59 | 60 | ready := make(chan bool, 1) 61 | done := make(chan bool, 1) 62 | 63 | // Send data from "my" side 64 | go func() { 65 | <-ready 66 | con, err := net.Dial("udp", Host+Port) 67 | assert.Nil(t, err) 68 | udp.TransferPackets(con, in, out) 69 | done <- true 70 | }() 71 | 72 | // Start server on the "other" side 73 | con, err := net.ListenPacket("udp", Port) 74 | assert.Nil(t, err) 75 | ready <- true 76 | 77 | // Read data on the "other" side 78 | buf := make([]byte, 1024) 79 | n, a, err := con.ReadFrom(buf) 80 | assert.Nil(t, err) 81 | assert.Equal(t, Input, string(buf[0:n])) 82 | 83 | // Send data from the "other" side 84 | n, err = con.WriteTo([]byte(InputFromOtherSide), a) 85 | assert.Nil(t, err) 86 | _, err = con.WriteTo([]byte("~.\n"), a) 87 | assert.Nil(t, err) 88 | err = con.Close() 89 | assert.Nil(t, err) 90 | <-done 91 | assert.Equal(t, InputFromOtherSide, string(out.Bytes()[0:n])) 92 | } 93 | -------------------------------------------------------------------------------- /tcp/tcp.go: -------------------------------------------------------------------------------- 1 | package tcp 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "net" 7 | "os" 8 | ) 9 | 10 | // Progress indicates transfer status 11 | type Progress struct { 12 | direction string 13 | bytes uint64 14 | } 15 | 16 | // TransferStreams launches two read-write goroutines and waits for signal from them 17 | func TransferStreams(con net.Conn, in io.Reader, out io.Writer) { 18 | defer func() { 19 | con.Close() 20 | }() 21 | c := make(chan Progress) 22 | 23 | // Read from input and send to connection 24 | go func() { 25 | n, err := io.Copy(con, in) 26 | if err != nil { 27 | log.Printf("[%s]: ERROR: %s\n", con.RemoteAddr(), err) 28 | } 29 | c <- Progress{ 30 | direction: "sent to connection", 31 | bytes: uint64(n), 32 | } 33 | }() 34 | 35 | // Read from connection and send to output 36 | go func() { 37 | n, err := io.Copy(out, con) 38 | if err != nil { 39 | log.Printf("[%s]: ERROR: %s\n", con.RemoteAddr(), err) 40 | } 41 | 42 | c <- Progress{ 43 | direction: "received from connection", 44 | bytes: uint64(n), 45 | } 46 | }() 47 | 48 | p := <-c 49 | log.Printf("TCP %s: %d bytes has been %s\n", con.RemoteAddr(), p.bytes, p.direction) 50 | p = <-c 51 | log.Printf("TCP %s: %d bytes has been %s\n", con.RemoteAddr(), p.bytes, p.direction) 52 | } 53 | 54 | // StartServer starts TCP listener 55 | func StartServer(proto string, port string) { 56 | ln, err := net.Listen(proto, port) 57 | if err != nil { 58 | log.Fatalln(err) 59 | } 60 | log.Println("Listening on", proto+port) 61 | con, err := ln.Accept() 62 | if err != nil { 63 | log.Fatalln(err) 64 | } 65 | log.Printf("[%s]: Connection has been opened\n", con.RemoteAddr()) 66 | TransferStreams(con, os.Stdin, os.Stdout) 67 | } 68 | 69 | // StartClient starts TCP connector 70 | func StartClient(proto string, host string, port string) { 71 | con, err := net.Dial(proto, host+port) 72 | if err != nil { 73 | log.Fatalln(err) 74 | } 75 | log.Println("Connected to", host+port) 76 | TransferStreams(con, os.Stdin, os.Stdout) 77 | } 78 | -------------------------------------------------------------------------------- /udp/udp.go: -------------------------------------------------------------------------------- 1 | package udp 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "net" 7 | "os" 8 | ) 9 | 10 | const ( 11 | // BufferLimit specifies buffer size that is sufficient to handle full-size UDP datagram or TCP segment in one step 12 | BufferLimit = 2<<16 - 1 13 | // DisconnectSequence is used to disconnect UDP sessions 14 | DisconnectSequence = "~." 15 | ) 16 | 17 | // Progress indicates transfer status 18 | type Progress struct { 19 | remoteAddr net.Addr 20 | direction string 21 | bytes uint64 22 | } 23 | 24 | // TransferPackets launches receive goroutine first, wait for address from it (if needed), launches send goroutine then 25 | func TransferPackets(con net.Conn, in io.Reader, out io.Writer) { 26 | defer func() { 27 | con.Close() 28 | }() 29 | 30 | c := make(chan Progress) 31 | 32 | // Read from Reader and write to Writer until EOF. 33 | // ra is an address to whom packets must be sent in listen mode. 34 | copy := func(r io.Reader, w io.Writer, ra net.Addr) { 35 | buf := make([]byte, BufferLimit) 36 | bytes := uint64(0) 37 | var n int 38 | var err error 39 | var addr net.Addr 40 | var direction string 41 | 42 | for { 43 | // Read 44 | if con, ok := r.(*net.UDPConn); ok { 45 | n, addr, err = con.ReadFrom(buf) 46 | // In listen mode remote address is unknown until read from connection. 47 | // So we must inform caller function with received remote address. 48 | if con.RemoteAddr() == nil && ra == nil { 49 | ra = addr 50 | c <- Progress{remoteAddr: ra} 51 | } 52 | } else { 53 | n, err = r.Read(buf) 54 | } 55 | if err != nil { 56 | if err != io.EOF { 57 | log.Printf("[%s]: ERROR: %s\n", ra, err) 58 | } 59 | break 60 | } 61 | if string(buf[0:n-1]) == DisconnectSequence { 62 | break 63 | } 64 | 65 | // Write 66 | if con, ok := w.(*net.UDPConn); ok && con.RemoteAddr() == nil { 67 | // Connection remote address must be nil otherwise "WriteTo with pre-connected connection" will be thrown 68 | n, err = con.WriteTo(buf[0:n], ra) 69 | } else { 70 | n, err = w.Write(buf[0:n]) 71 | } 72 | if err != nil { 73 | log.Printf("[%s]: ERROR: %s\n", ra, err) 74 | break 75 | } 76 | bytes += uint64(n) 77 | } 78 | 79 | if _, ok := r.(*net.UDPConn); ok { 80 | direction = "received from connection" 81 | } else { 82 | direction = "sent to connection" 83 | } 84 | c <- Progress{ 85 | direction: direction, 86 | bytes: bytes, 87 | } 88 | } 89 | 90 | ra := con.RemoteAddr() 91 | go copy(con, out, ra) 92 | 93 | // If connection hasn't got remote address then wait for it from receiver goroutine 94 | if ra == nil { 95 | p := <-c 96 | ra = p.remoteAddr 97 | log.Printf("[%s]: Datagram has been received\n", ra) 98 | } 99 | go copy(in, con, ra) 100 | 101 | p := <-c 102 | log.Printf("UDP %s: %d bytes has been %s\n", ra, p.bytes, p.direction) 103 | p = <-c 104 | log.Printf("UDP %s: %d bytes has been %s\n", ra, p.bytes, p.direction) 105 | } 106 | 107 | // StartServer starts UDP listener 108 | func StartServer(proto string, port string) { 109 | addr, err := net.ResolveUDPAddr(proto, port) 110 | if err != nil { 111 | log.Fatalln(err) 112 | } 113 | con, err := net.ListenUDP(proto, addr) 114 | if err != nil { 115 | log.Fatalln(err) 116 | } 117 | log.Println("Listening on", proto+port) 118 | // This connection doesn't know remote address yet 119 | TransferPackets(con, os.Stdin, os.Stdout) 120 | } 121 | 122 | // StartClient starts UDP connector 123 | func StartClient(proto string, host string, port string) { 124 | addr, err := net.ResolveUDPAddr(proto, host+port) 125 | if err != nil { 126 | log.Fatalln(err) 127 | } 128 | con, err := net.DialUDP(proto, nil, addr) 129 | if err != nil { 130 | log.Fatalln(err) 131 | } 132 | log.Println("Sending datagrams to", host+port) 133 | TransferPackets(con, os.Stdin, os.Stdout) 134 | } 135 | --------------------------------------------------------------------------------