├── .gitignore ├── .goreleaser.yml ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── LICENSE ├── README.md ├── check.sh ├── discover ├── aws.go ├── azure.go ├── digitalocean.go ├── discover.go ├── gcp.go └── util.go ├── go.mod ├── main.go └── release.sh /.gitignore: -------------------------------------------------------------------------------- 1 | /netdiscover 2 | /netdiscover.linux.amd64 3 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | project_name: Network Discovery tool 2 | builds: 3 | - binary: netdiscover 4 | env: 5 | - CGO_ENABLED=0 6 | goos: 7 | - linux 8 | - darwin 9 | - windows 10 | goarch: 11 | - amd64 12 | 13 | archives: 14 | - id: netdiscover 15 | format: binary 16 | name_template: "{{ .Binary }}.{{ .Os }}.{{ .Arch }}" 17 | checksum: 18 | name_template: 'checksums.txt' 19 | snapshot: 20 | name_template: "{{ .Tag }}-next" 21 | changelog: 22 | sort: asc 23 | filters: 24 | exclude: 25 | - '^docs:' 26 | - '^doc:' 27 | - '^test:' 28 | 29 | dockers: 30 | - image_templates: 31 | - "cycoresystems/netdiscover:{{ .Tag }}" 32 | - "cycoresystems/netdiscover:v{{ .Major }}" 33 | - "cycoresystems/netdiscover:v{{ .Major }}.{{ .Minor }}" 34 | - "cycoresystems/netdiscover:latest" 35 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | env: 3 | - GO111MODULE=on 4 | go: 5 | - "1.14" 6 | install: 7 | - go mod tidy 8 | - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin v1.28.2 9 | - curl -sfL https://github.com/goreleaser/goreleaser/releases/download/v0.139.0/goreleaser_Linux_x86_64.tar.gz | tar xfz - -C $GOPATH/bin goreleaser 10 | script: bash check.sh 11 | services: 12 | - docker 13 | deploy: 14 | - provider: script 15 | skip_cleanup: true 16 | script: bash release.sh 17 | on: 18 | tags: true 19 | condition: $TRAVIS_OS_NAME = linux 20 | 21 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at sys@cycoresys.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ulexus/go-minimal 2 | COPY netdiscover /app 3 | -------------------------------------------------------------------------------- /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 2018 CyCore Systems, Inc. 190 | 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Netdiscover 2 | [![Build Status](https://travis-ci.org/CyCoreSystems/netdiscover.png)](https://travis-ci.org/CyCoreSystems/netdiscover) [![](https://godoc.org/github.com/CyCoreSystems/netdiscover/discover?status.svg)](http://godoc.org/github.com/CyCoreSystems/netdiscover/discover) 3 | 4 | Netdiscover is a CLI tool and Golang library by which network information may 5 | be discovered on various cloud platforms and bare metal installations. The 6 | typical use case is, when running inside Kubernetes or a container, to discover 7 | the public IP and/or hostname of the node on which the container is running. 8 | This is commonly necessary to configure VoIP applications. 9 | 10 | ## CLI tool 11 | 12 | In the root directory can be found a CLI tool which can be used to query network 13 | information. There are two options: 14 | 15 | * `-provider `: if a cloud provider is specified, that provider's 16 | metadata services will be used to determine the network information. 17 | Otherwise, a best-effort approach will be used. 18 | * `-field `: if a field is specified, only that particular network 19 | detail will be returned. Otherwise, a JSON object will be returned 20 | containing all network information which was discovered. 21 | 22 | ## Supported providers 23 | 24 | Currently, this tool supports four cloud providers: 25 | 26 | * `aws`: Amazon Web Services 27 | * `azure`: Microsoft Azure Cloud 28 | * `do`: Digital Ocean 29 | * `gcp`: Google Cloud Platform 30 | * ``: general discovery (baremetal) 31 | 32 | Not all providers support all network details. General discovery should be used 33 | for baremetal or other unsupported environments. It will use the public service 34 | (jsonip.io) to determine the necessary network data. 35 | 36 | I am happy to accept pull requests to implement more providers. 37 | 38 | ## Supported Fields 39 | 40 | Currently, this tool supports four network data fields: 41 | 42 | * `hostname`: the public hostname of the node 43 | * `privatev4`: the private (internal) IPv4 address of the node 44 | * `publicv4`: the public (external) IPv4 address of the node 45 | * `publicv6`: the public (external) IPv6 address of the node 46 | 47 | Note that for DigitalOcean\'s hostname feature to work as expected, you need to 48 | change the Droplet name to the fully-qualified domain name of the host. Doing 49 | so will also cause DigitalOcean to register the reverse DNS lookup for the 50 | Droplet\'s IP address, so this should generally be done, anyway. 51 | 52 | 53 | ## Examples 54 | 55 | Retrieve the public version 4 IP address of the node instance on GCP: 56 | 57 | ``` 58 | netdiscover -provider gcp -field publicv4 59 | ``` 60 | 61 | Retrieve all network information on Amazon Web Services platform: 62 | 63 | ``` 64 | netdiscover -provider aws 65 | ``` 66 | 67 | Retrieve the version 6 IP address of a baremetal machine: 68 | 69 | ``` 70 | netdiscover -field publicv6 71 | ``` 72 | 73 | -------------------------------------------------------------------------------- /check.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | golangci-lint run 3 | go test ./... 4 | go build ./... 5 | go build 6 | -------------------------------------------------------------------------------- /discover/aws.go: -------------------------------------------------------------------------------- 1 | package discover 2 | 3 | import ( 4 | "net" 5 | ) 6 | 7 | const ( 8 | awsPrivateIPv4URL = "http://169.254.169.254/latest/meta-data/local-ipv4" 9 | awsPublicIPv4URL = "http://169.254.169.254/latest/meta-data/public-ipv4" 10 | awsHostnameURL = "http://169.254.169.254/latest/meta-data/public-hostname" 11 | ) 12 | 13 | // NewAWSDiscoverer returns a new Amazon Web Services network discoverer 14 | func NewAWSDiscoverer() Discoverer { 15 | return NewDiscoverer( 16 | PrivateIPv4DiscovererOption(awsPrivateIPv4), 17 | PublicIPv4DiscovererOption(awsPublicIPv4), 18 | PublicHostnameDiscovererOption(awsHostname), 19 | ) 20 | 21 | } 22 | 23 | func awsPrivateIPv4() (net.IP, error) { 24 | return StandardIPFromHTTP(awsPrivateIPv4URL, nil) 25 | } 26 | 27 | func awsPublicIPv4() (net.IP, error) { 28 | return StandardIPFromHTTP(awsPublicIPv4URL, nil) 29 | } 30 | 31 | func awsHostname() (string, error) { 32 | return StandardHostnameFromHTTP(awsHostnameURL, nil) 33 | } 34 | -------------------------------------------------------------------------------- /discover/azure.go: -------------------------------------------------------------------------------- 1 | package discover 2 | 3 | import ( 4 | "net" 5 | ) 6 | 7 | const ( 8 | azurePrivateIPv4URL = "http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/privateIpAddress?api-version=2017-08-01&format=text" 9 | azurePublicIPv4URL = "http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-08-01&format=text" 10 | ) 11 | 12 | // NewAzureDiscoverer returns a new Google Cloud Platform network discoverer 13 | func NewAzureDiscoverer() Discoverer { 14 | return NewDiscoverer( 15 | PrivateIPv4DiscovererOption(azurePrivateIPv4), 16 | PublicIPv4DiscovererOption(azurePublicIPv4), 17 | ) 18 | } 19 | 20 | func azurePrivateIPv4() (net.IP, error) { 21 | return StandardIPFromHTTP(azurePrivateIPv4URL, map[string]string{"Metadata": "true"}) 22 | } 23 | 24 | func azurePublicIPv4() (net.IP, error) { 25 | return StandardIPFromHTTP(azurePublicIPv4URL, map[string]string{"Metadata": "true"}) 26 | } 27 | -------------------------------------------------------------------------------- /discover/digitalocean.go: -------------------------------------------------------------------------------- 1 | package discover 2 | 3 | // TODO: decide out how, when, and if to return the Floating IP (URLs noted below) 4 | 5 | import ( 6 | "net" 7 | ) 8 | 9 | const ( 10 | doHostnameURL = "http://169.254.169.254/metadata/v1/hostname" 11 | doPrivateIPv4URL = "http://169.254.169.254/metadata/v1/interfaces/private/0/ipv4/address" 12 | doPublicIPv4URL = "http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address" 13 | // doFloatingPublicIPv4EnabledURL = "http://169.254.169.254/metadata/v1/floating_ip/ipv4/active" 14 | // doFloatingPublicIPv4URL = "http://169.254.169.254/metadata/v1/interfaces/public/0/anchor_ipv4/address" 15 | doPublicIPv6URL = "http://169.254.169.254/metadata/v1/interfaces/public/0/ipv6/address" 16 | ) 17 | 18 | // NewDigitalOceanDiscoverer returns a new Digital Ocean network discoverer 19 | func NewDigitalOceanDiscoverer() Discoverer { 20 | return NewDiscoverer( 21 | PublicHostnameDiscovererOption(doHostname), 22 | PrivateIPv4DiscovererOption(doPrivateIPv4), 23 | PublicIPv4DiscovererOption(doPublicIPv4), 24 | PublicIPv6DiscovererOption(doPublicIPv6), 25 | ) 26 | } 27 | 28 | func doHostname() (string, error) { 29 | return StandardHostnameFromHTTP(doHostnameURL, nil) 30 | } 31 | 32 | func doPrivateIPv4() (net.IP, error) { 33 | return StandardIPFromHTTP(doPrivateIPv4URL, nil) 34 | } 35 | 36 | func doPublicIPv4() (net.IP, error) { 37 | return StandardIPFromHTTP(doPublicIPv4URL, nil) 38 | } 39 | 40 | func doPublicIPv6() (net.IP, error) { 41 | return StandardIPFromHTTP(doPublicIPv6URL, nil) 42 | } 43 | -------------------------------------------------------------------------------- /discover/discover.go: -------------------------------------------------------------------------------- 1 | package discover 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "net" 8 | "net/http" 9 | "strings" 10 | ) 11 | 12 | // Discoverer describes an interface by which network details may be discovered 13 | type Discoverer interface { 14 | 15 | // Hostname returns the public hostname. 16 | Hostname() (string, error) 17 | 18 | // PrivateIPv4 returns the private IPv4 address. 19 | PrivateIPv4() (net.IP, error) 20 | 21 | // PublicIPv4 returns the public IPv4 address. 22 | PublicIPv4() (net.IP, error) 23 | 24 | // PublicIPv6 returns the public IPv6 address. 25 | PublicIPv6() (net.IP, error) 26 | } 27 | 28 | // GenericDiscoverer provides a flexible network detail discoverer, allowing 29 | // one to supply URLs and metadata for specific providers. Any value which is 30 | // not set will be attempted by the default process. 31 | type genericDiscoverer struct { 32 | opts *DiscovererOptions 33 | } 34 | 35 | // DiscovererOptions describes the options used to construct a generic discoverer. 36 | type DiscovererOptions struct { 37 | getHostname func() (string, error) 38 | getPrivateIPv4 func() (net.IP, error) 39 | getPublicIPv4 func() (net.IP, error) 40 | getPublicIPv6 func() (net.IP, error) 41 | } 42 | 43 | // DiscovererOption is a function which configures a GenericDiscoverer. 44 | type DiscovererOption func(o *DiscovererOptions) 45 | 46 | // PrivateIPv4DiscovererOption retuns a DiscovererOption which sets the Private 47 | // IPv4 address discovery function. 48 | func PrivateIPv4DiscovererOption(f func() (net.IP, error)) func(*DiscovererOptions) { 49 | return func(o *DiscovererOptions) { 50 | if f == nil { 51 | return 52 | } 53 | o.getPrivateIPv4 = f 54 | } 55 | } 56 | 57 | // PublicIPv4DiscovererOption returns a DiscovererOption which sets the Public 58 | // IPv4 address discovery function. 59 | func PublicIPv4DiscovererOption(f func() (net.IP, error)) func(*DiscovererOptions) { 60 | return func(o *DiscovererOptions) { 61 | if f == nil { 62 | return 63 | } 64 | o.getPublicIPv4 = f 65 | } 66 | } 67 | 68 | // PublicIPv6DiscovererOption returns a DiscovererOption which sets the Public 69 | // IPv6 address discovery function. 70 | func PublicIPv6DiscovererOption(f func() (net.IP, error)) func(*DiscovererOptions) { 71 | return func(o *DiscovererOptions) { 72 | if f == nil { 73 | return 74 | } 75 | o.getPublicIPv6 = f 76 | } 77 | } 78 | 79 | // PublicHostnameDiscovererOption returns a DiscovererOption which sets the Public 80 | // Hostname discovery function. 81 | func PublicHostnameDiscovererOption(f func() (string, error)) func(*DiscovererOptions) { 82 | return func(o *DiscovererOptions) { 83 | if f == nil { 84 | return 85 | } 86 | o.getHostname = f 87 | } 88 | } 89 | 90 | // NewDiscoverer creates a new network discoverer 91 | func NewDiscoverer(opts ...DiscovererOption) Discoverer { 92 | o := &DiscovererOptions{ 93 | getPrivateIPv4: defaultPrivateIPv4, 94 | getPublicIPv4: defaultPublicIPv4, 95 | getPublicIPv6: defaultPublicIPv6, 96 | } 97 | 98 | for _, opt := range opts { 99 | if opt != nil { 100 | opt(o) 101 | } 102 | } 103 | 104 | if o.getHostname == nil { 105 | o.getHostname = func() (string, error) { 106 | return defaultHostname(o.getPublicIPv4) 107 | } 108 | } 109 | 110 | return &genericDiscoverer{opts: o} 111 | } 112 | 113 | func (d *genericDiscoverer) Hostname() (string, error) { 114 | if d == nil || d.opts == nil { 115 | return "", errors.New("discoverer not created") 116 | } 117 | if d.opts.getHostname == nil { 118 | return "", errors.New("no hostname discoverer") 119 | } 120 | return d.opts.getHostname() 121 | } 122 | 123 | func (d *genericDiscoverer) PrivateIPv4() (net.IP, error) { 124 | if d == nil || d.opts == nil { 125 | return nil, errors.New("discoverer not created") 126 | } 127 | if d.opts.getPrivateIPv4 == nil { 128 | return nil, errors.New("no private IPv4 discoverer") 129 | } 130 | return d.opts.getPrivateIPv4() 131 | } 132 | 133 | func (d *genericDiscoverer) PublicIPv4() (net.IP, error) { 134 | if d == nil || d.opts == nil { 135 | return nil, errors.New("discoverer not created") 136 | } 137 | if d.opts.getPublicIPv4 == nil { 138 | return nil, errors.New("no public IPv4 discoverer") 139 | } 140 | return d.opts.getPublicIPv4() 141 | } 142 | 143 | func (d *genericDiscoverer) PublicIPv6() (net.IP, error) { 144 | if d == nil || d.opts == nil { 145 | return nil, errors.New("discoverer not created") 146 | } 147 | if d.opts.getPublicIPv6 == nil { 148 | return nil, errors.New("no public IPv6 discoverer") 149 | } 150 | return d.opts.getPublicIPv6() 151 | } 152 | 153 | func defaultPublicIPv4() (net.IP, error) { 154 | resp, err := http.Get("http://ipv4.jsonip.io") 155 | if err != nil { 156 | return nil, err 157 | } 158 | defer resp.Body.Close() // nolint: errcheck 159 | 160 | dec := json.NewDecoder(resp.Body) 161 | 162 | type response struct { 163 | Address string `json:"address"` 164 | } 165 | data := new(response) 166 | 167 | err = dec.Decode(data) 168 | if err != nil { 169 | return nil, fmt.Errorf("failed to parse response: %v", err) 170 | } 171 | 172 | ip := net.ParseIP(data.Address) 173 | if ip == nil { 174 | return nil, fmt.Errorf("failed to parse address: %s", data.Address) 175 | } 176 | 177 | return ip, nil 178 | } 179 | 180 | func defaultPublicIPv6() (net.IP, error) { 181 | resp, err := http.Get("http://ipv6.jsonip.io") 182 | if err != nil { 183 | return nil, err 184 | } 185 | defer resp.Body.Close() // nolint: errcheck 186 | 187 | dec := json.NewDecoder(resp.Body) 188 | 189 | type response struct { 190 | Address string `json:"address"` 191 | } 192 | data := new(response) 193 | 194 | err = dec.Decode(data) 195 | if err != nil { 196 | return nil, fmt.Errorf("failed to parse response: %v", err) 197 | } 198 | 199 | ip := net.ParseIP(data.Address) 200 | if ip == nil { 201 | return nil, fmt.Errorf("failed to parse address: %s", data.Address) 202 | } 203 | 204 | return ip, nil 205 | } 206 | 207 | // nolint: gocyclo 208 | func defaultPrivateIPv4() (net.IP, error) { 209 | netifs, err := net.Interfaces() 210 | if err != nil { 211 | return nil, fmt.Errorf("failed to get list of local interfaces: %v", err) 212 | } 213 | 214 | for _, i := range netifs { 215 | 216 | // Skip docker interfaces 217 | if strings.HasPrefix(i.Name, "docker") { 218 | continue 219 | } 220 | 221 | addresses, err := i.Addrs() 222 | if err != nil { 223 | continue // next interface 224 | } 225 | 226 | for _, addrIf := range addresses { 227 | a := addrIf.String() 228 | 229 | tmpIP, _, err := net.ParseCIDR(a) 230 | if err != nil || tmpIP == nil { 231 | continue // next address 232 | } 233 | 234 | if tmpIP.IsLoopback() { 235 | break // next interface 236 | } 237 | 238 | if !tmpIP.IsGlobalUnicast() { 239 | // multicast, link-local, etc 240 | continue // next address 241 | } 242 | 243 | if toIPv4 := tmpIP.To4(); toIPv4 == nil { 244 | // Not an IPv4 address 245 | continue // next address 246 | } 247 | 248 | return tmpIP, nil 249 | } 250 | } 251 | 252 | return nil, errors.New("valid address not found") 253 | } 254 | 255 | func defaultHostname(ipFunc func() (net.IP, error)) (string, error) { 256 | 257 | if ipFunc == nil { 258 | return "", errors.New("no public IP discovery function") 259 | } 260 | 261 | ip, err := ipFunc() 262 | if err != nil { 263 | return "", fmt.Errorf("failed to obtain public IP: %v", err) 264 | } 265 | 266 | names, err := net.LookupAddr(ip.String()) 267 | if err != nil { 268 | return "", fmt.Errorf("failed to reverse-lookup ip address: %v", err) 269 | } 270 | 271 | for _, name := range names { 272 | if len(name) < 6 { 273 | // implausibly short name 274 | continue 275 | } 276 | if !strings.Contains(name, ".") { 277 | // implausible TLD or local-only hostname 278 | continue 279 | } 280 | if strings.HasSuffix(name, ".local") { 281 | continue 282 | } 283 | 284 | return strings.TrimSuffix(name, "."), err 285 | } 286 | 287 | return "", fmt.Errorf("failed to discover valid public name") 288 | } 289 | -------------------------------------------------------------------------------- /discover/gcp.go: -------------------------------------------------------------------------------- 1 | package discover 2 | 3 | import ( 4 | "net" 5 | ) 6 | 7 | const ( 8 | gcpPrivateIPv4URL = "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/ip" 9 | gcpPublicIPv4URL = "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip" 10 | gcpHostnameURL = "http://metadata.google.internal/computeMetadata/v1/instance/hostname" 11 | ) 12 | 13 | // NewGCPDiscoverer returns a new Google Cloud Platform network discoverer 14 | func NewGCPDiscoverer() Discoverer { 15 | return NewDiscoverer( 16 | PrivateIPv4DiscovererOption(gcpPrivateIPv4), 17 | PublicIPv4DiscovererOption(gcpPublicIPv4), 18 | PublicHostnameDiscovererOption(gcpHostname), 19 | ) 20 | } 21 | 22 | func gcpPrivateIPv4() (net.IP, error) { 23 | return StandardIPFromHTTP(gcpPrivateIPv4URL, map[string]string{"Metadata-Flavor": "Google"}) 24 | } 25 | 26 | func gcpPublicIPv4() (net.IP, error) { 27 | return StandardIPFromHTTP(gcpPublicIPv4URL, map[string]string{"Metadata-Flavor": "Google"}) 28 | } 29 | 30 | func gcpHostname() (string, error) { 31 | return StandardHostnameFromHTTP(gcpHostnameURL, map[string]string{"Metadata-Flavor": "Google"}) 32 | } 33 | -------------------------------------------------------------------------------- /discover/util.go: -------------------------------------------------------------------------------- 1 | package discover 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "io/ioutil" 7 | "net" 8 | "net/http" 9 | ) 10 | 11 | // ParseIPv4FromBody reads from a reader (such as an http.Body) and tries to 12 | // parse the IPv4 IP address contained therein. 13 | func ParseIPv4FromBody(in io.Reader) (net.IP, error) { 14 | 15 | data, err := ioutil.ReadAll(in) 16 | if err != nil { 17 | return nil, fmt.Errorf("failed to read response: %v", err) 18 | } 19 | 20 | if len(data) < 8 || len(data) > 42 { 21 | return nil, fmt.Errorf("invalid response: %s", string(data)) 22 | } 23 | 24 | ip := net.ParseIP(string(data)) 25 | if ip == nil { 26 | return nil, fmt.Errorf("failed to parse IP: %s", string(data)) 27 | } 28 | 29 | return ip, nil 30 | } 31 | 32 | // StandardIPFromHTTP queries an HTTP URL and returns the IP address contained within its response. Headers are optional. 33 | func StandardIPFromHTTP(url string, headers map[string]string) (net.IP, error) { 34 | 35 | req, err := http.NewRequest("GET", url, nil) 36 | if err != nil { 37 | return nil, fmt.Errorf("failed to construct HTTP request: %v", err) 38 | } 39 | 40 | for k, v := range headers { 41 | req.Header.Add(k, v) 42 | } 43 | 44 | resp, err := http.DefaultClient.Do(req) 45 | if err != nil { 46 | return nil, err 47 | } 48 | defer resp.Body.Close() // nolint: errcheck 49 | 50 | if resp.StatusCode < 200 || resp.StatusCode > 299 { 51 | return nil, fmt.Errorf("non-2XX response: (%d) %s", resp.StatusCode, resp.Status) 52 | } 53 | 54 | return ParseIPv4FromBody(resp.Body) 55 | } 56 | 57 | // StandardHostnameFromHTTP queries an HTTP URL and returns the hostname contained within its response. Headers are optional. 58 | func StandardHostnameFromHTTP(url string, headers map[string]string) (string, error) { 59 | 60 | req, err := http.NewRequest("GET", url, nil) 61 | if err != nil { 62 | return "", fmt.Errorf("failed to construct HTTP request: %v", err) 63 | } 64 | 65 | for k, v := range headers { 66 | req.Header.Add(k, v) 67 | } 68 | 69 | resp, err := http.DefaultClient.Do(req) 70 | if err != nil { 71 | return "", err 72 | } 73 | defer resp.Body.Close() // nolint: errcheck 74 | 75 | if resp.StatusCode < 200 || resp.StatusCode > 299 { 76 | return "", fmt.Errorf("non-2XX response: (%d) %s", resp.StatusCode, resp.Status) 77 | } 78 | 79 | body, err := ioutil.ReadAll(resp.Body) 80 | if err != nil { 81 | return "", fmt.Errorf("failed to read response: %v", err) 82 | } 83 | if len(body) < 4 { 84 | return "", fmt.Errorf("hostname implausibly short: %s", string(body)) 85 | } 86 | 87 | return string(body), nil 88 | } 89 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/CyCoreSystems/netdiscover 2 | 3 | go 1.14 4 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "flag" 6 | "fmt" 7 | "log" 8 | "os" 9 | 10 | "github.com/CyCoreSystems/netdiscover/discover" 11 | ) 12 | 13 | var ( 14 | debug bool 15 | provider string 16 | retField string 17 | ) 18 | 19 | func init() { 20 | flag.BoolVar(&debug, "debug", false, `debug mode`) 21 | flag.StringVar(&provider, "provider", "", `provider type. Options are: "aws", "azure", "do", gcp"`) 22 | flag.StringVar(&retField, "field", "", `return only a single field. Options are: "hostname", "publicv4", publicv6", "privatev4"`) 23 | } 24 | 25 | // Response describes the response from an unlimited discovery 26 | type Response struct { 27 | // Hostname is the public hostname of the node 28 | Hostname string `json:"hostname"` 29 | 30 | // PrivateIPv4 is the private (internal) IPv4 address of the node 31 | PrivateIPv4 string `json:"private_ipv4"` 32 | 33 | // PublicIPv4 is the public (external) IPv4 address of the node 34 | PublicIPv4 string `json:"public_ipv4"` 35 | 36 | // PublicIPv6 is the public (external) IPv6 address of the node 37 | PublicIPv6 string `json:"public_ipv6"` 38 | } 39 | 40 | // nolint: gocyclo 41 | func main() { 42 | if os.Getenv("CLOUD_PROVIDER") != "" { 43 | provider = os.Getenv("CLOUD_PROVIDER") 44 | } 45 | 46 | flag.Parse() 47 | 48 | var discoverer discover.Discoverer 49 | switch provider { 50 | case "aws": 51 | discoverer = discover.NewAWSDiscoverer() 52 | case "azure": 53 | discoverer = discover.NewAzureDiscoverer() 54 | case "do": 55 | discoverer = discover.NewDigitalOceanDiscoverer() 56 | case "gcp": 57 | discoverer = discover.NewGCPDiscoverer() 58 | default: 59 | discoverer = discover.NewDiscoverer() 60 | } 61 | 62 | if retField != "" { 63 | switch retField { 64 | case "hostname": 65 | h, err := discoverer.Hostname() 66 | if err != nil { 67 | log.Fatal(err) 68 | } 69 | fmt.Println(h) 70 | os.Exit(0) 71 | case "privatev4": 72 | ip, err := discoverer.PrivateIPv4() 73 | if err != nil { 74 | log.Fatal(err) 75 | } 76 | fmt.Println(ip.String()) 77 | os.Exit(0) 78 | case "publicv4": 79 | ip, err := discoverer.PublicIPv4() 80 | if err != nil { 81 | log.Fatal(err) 82 | } 83 | fmt.Println(ip.String()) 84 | os.Exit(0) 85 | case "publicv6": 86 | ip, err := discoverer.PublicIPv6() 87 | if err != nil { 88 | log.Fatal(err) 89 | } 90 | fmt.Println(ip.String()) 91 | os.Exit(0) 92 | default: 93 | log.Fatal("valid fields are: hostname, privatev4, publicv4, publicv6") 94 | } 95 | } 96 | 97 | var err error 98 | ret := new(Response) 99 | 100 | ret.Hostname, err = discoverer.Hostname() 101 | if err != nil && debug { 102 | log.Println("failed to get hostname:", err) 103 | } 104 | 105 | privateIP, err := discoverer.PrivateIPv4() 106 | if err == nil { 107 | ret.PrivateIPv4 = privateIP.String() 108 | } else if debug { 109 | log.Println("failed to get private IPv4 address:", err) 110 | } 111 | 112 | publicIP, err := discoverer.PublicIPv4() 113 | if err == nil { 114 | ret.PublicIPv4 = publicIP.String() 115 | } else if debug { 116 | log.Println("failed to get public IPv4 address:", err) 117 | } 118 | 119 | publicIPv6, err := discoverer.PublicIPv6() 120 | if err == nil { 121 | ret.PublicIPv6 = publicIPv6.String() 122 | } else if debug { 123 | log.Println("failed to get public IPv6 address:", err) 124 | } 125 | 126 | enc := json.NewEncoder(os.Stdout) 127 | 128 | if err := enc.Encode(ret); err != nil { 129 | log.Fatal("failed to encode response:", ret) 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Only run if we are inside Travis-CI 4 | if [ ! -e $CI ]; then 5 | echo "Logging in to Docker..." 6 | echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin 7 | 8 | # Create the release 9 | echo "Creating release..." 10 | goreleaser release 11 | fi 12 | 13 | --------------------------------------------------------------------------------