ipify

package
v1.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 1, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package myipcom returns your Internet-facing IPv4 or IPv6 address, sourced from the ipify API. https://www.ipify.org © Ben Garrett https://github.com/bengarrett/myip

Index

Examples

Constants

View Source
const (
	Linkv4 = "https://api.ipify.org"
	Linkv6 = "https://api6.ipify.org"
)

Variables

View Source
var (
	ErrNoIP    = errors.New("ip address is empty")
	ErrInvalid = errors.New("ip address is invalid")
	ErrRequest = errors.New("ipify.org error")
	ErrStatus  = errors.New("unusual ipify.org server response")
)

Functions

func IPv4

func IPv4(ctx context.Context, cancel context.CancelFunc) (string, error)

IPv4 returns the clients online IP address.

Example

ExampleIPv4 demonstrates an IPv4 address request with a 5 second timeout. Output: true.

package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"time"

	"github.com/bengarrett/myip/pkg/ipify"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	s, err := ipify.IPv4(ctx, cancel)
	if err != nil {
		log.Printf("\n%s\n", err)
	}
	fmt.Println(net.ParseIP(s) != nil)
}
Output:

func IPv6

func IPv6(ctx context.Context, cancel context.CancelFunc) (string, error)

IPv6 returns the clients online IP address. Using this on a network that does not support IPv6 will result in an error.

Example

ExampleIPv6 demonstrates cocurrent IPv4 and IPv6 address requests with a 5 second timeout.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/bengarrett/myip/pkg/ipify"
)

func main() {
	ctx4, cancel4 := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel4()

	ctx6, cancel6 := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel6()

	s4 := make(chan string)
	s6 := make(chan string)

	go func() {
		s, err := ipify.IPv4(ctx4, cancel4)
		if err != nil {
			log.Printf("\n%s\n", err)
		}
		s4 <- s
	}()

	go func() {
		s, err := ipify.IPv6(ctx6, cancel6)
		if err != nil {
			log.Printf("\n%s\n", err)
		}
		s6 <- s
	}()

	ip4 := <-s4
	ip6 := <-s6
	fmt.Println(ip4)
	fmt.Println(ip6)
}
Output:

func Request

func Request(ctx context.Context, cancel context.CancelFunc, url string) (string, error)

Request the ipify API and return a valid IPv4 or IPv6 address.

func RequestB

func RequestB(ctx context.Context, cancel context.CancelFunc, url string) ([]byte, error)

RequestB requests the ipify API and return the response body.

func Valid

func Valid(ip string) error

Valid returns nil if ip is a valid textual representation of an IP address.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL