Go combat--golang Get public IP, view intranet IP, detect IP type, verify IP range, IP address string and int conversion, judge by IP region state operator, etc.

Source: Internet
Author: User
Tags curl documentation ftp json postgresql redis reserved firewall


Life goes on, go go go ...



Previously, there was a reference to the standard library provided by Golang: NET Package



Go Language Learning Net package (the path to go) 


brief aftertaste net package



func Parseip






Func Parseip (s string) IP


Parseip parses S as an IP address, returning the result. The string s can is in dotted decimal ("192.0.2.1") or IPv6 ("2001:db8::68") Form. If S is not a valid textual representation of an IP address, PARSEIP returns nil.

func Interfaceaddrs


Func Interfaceaddrs () ([]addr, error)


Interfaceaddrs returns a list of the system ' s unicast interface addresses.



The returned list does not identify the associated interface; Use Interfaces and Interface.addrs for more detail.



type ipnet
An ipnet represents an IP network.






Type ipnet struct {
        IP   IP     //network number
        mask IPMask//network Mask
}



type IP

An IP was a single IP address, a slice of bytes. Functions in this package accept either 4-byte (IPV4) or 16-byte (IPV6) slices as input.



Note that the this documentation, referring to an IP address as an IPv4 address or an IPV6 address was a semantic property O f the address, not just the length of the byte slice:a 16-byte slice can still is an IPv4 address.






Type IP []byte


func IPv4





Func IPv4 (A, B, C, D byte) IP


IPV4 returns the IP address (in 16-byte form) of the IPV4 address a.b.c.d.



Donuts, see the documentation for more details: https://golang.org/pkg/net 



What is an extranet IP and intranet IP?





In the TCP/IP protocol, three IP address zones are reserved for private addresses with the following address ranges:
10.0.0.0/8:10.0.0.0~10.255.255.255
172.16.0.0/12:172.16.0.0~172.31.255.255
192.168.0.0/16:192.168.0.0~192.168.255.255





What is an intranet IP





Some small businesses or schools usually apply for a fixed IP address, and then use IP-sharing (IP sharing) to access the Internet through a company or school machine. And these enterprises or schools machine use IP address is intranet IP, intranet IP is in the planning IPV4 protocol, considering the IP address resources may be insufficient, specifically for the internal network design private IP address (or called reserved address), generally used intranet IP address is this form: 10.x.x.x, 172.16.x.x-172.31.x.x, 192.168.x.x and so on. It is important to note that the intranet computer can send connection requests to other computers on the Internet, but other computers on the Internet cannot send connection requests to computers in the intranet. We can usually build a website or FTP server on the intranet machine, and the external network can not access the site and FTP server, because of this.





What is a public network IP


A public IP is an IP address other than a reserved IP address that can be accessed freely with other computers on the Internet. What we usually call IP addresses, in fact, refers to the public network IP. Each computer on the Internet has a separate IP address that uniquely identifies a computer on the Internet. The IP address here refers to the public IP address.

How to understand that every computer on the Internet has a unique IP address


In fact, the Internet computer is through the "Public network ip+ intranet IP" to determine the only, as many buildings are 201 rooms, room number may be the same, but the building must be unique. Public network IP Address and intranet IP address also, different enterprises or schools may have the same intranet IP address, but their public network IP address must be different. So how do these businesses or schools ' computers share their IP addresses? This requires the use of the NAT (Network address translation) feature. When an internal computer wants to connect to the Internet, it first needs to use NAT technology to set the IP address in the internal computer packet to the public IP address of the NAT host and then to the Internet, although the internal computer uses a private IP address, but when the Internet is connected, It is possible to change the intranet IP address to the public IP address through NAT NAT technology, so that the intranet computer can request data from the Internet.

Get the public network IP

Baidu IP, you can view the public network IP

Curl command to view public IP

Curl IPINFO.IO/IP


get public IP via Http://myexternalip.com/raw


Func get_external () string {
    resp, err: = http. Get ("Http://myexternalip.com/raw")
    if err! = Nil {
        return "
    }
    Defer resp. Body.close ()
    content, _: = Ioutil. ReadAll (resp. Body)
    //buf: = new (bytes. Buffer)
    //buf. Readfrom (resp. Body)
    //s: = buf. String ()
    return string (content)
}
 






Func Getintranetip () {
    Addrs, err: = Net. Interfaceaddrs ()

    if err! = Nil {
        FMT. PRINTLN (ERR)
        OS. Exit (1)
    }

    for _, Address: = Range Addrs {

        //Check IP address to determine if loopback address if
        ipnet, OK: = Address. ( *net. Ipnet); OK &&!ipnet. Ip. Isloopback () {
            if ipnet. Ip. To4 ()! = nil {
                FMT. Println ("IP:", ipnet. Ip. String ())}}}}


Obtain the IP used by the DNS server 8.8.8.8:80





Func Getpulicip () string {
    Conn, _: = Net. Dial ("UDP", "8.8.8.8:80")
    defer Conn. Close ()
    localaddr: = conn. Localaddr (). String ()
    idx: = Strings. LastIndex (LOCALADDR, ":")
    return LOCALADDR[0:IDX]
}
 


Func Ispublicip (IP net. IP) bool {
    if IP. Isloopback () | | Ip. Islinklocalmulticast () | | Ip. Islinklocalunicast () {
        return false
    }
    if IP4: = IP. To4 (); Ip4! = Nil {
        switch true {case
        ip4[0] = =:
            return false case
        ip4[0] = = 172 && ip4[1] >= && ip4[1] <=:
            return false case
        ip4[0] = = 192 && ip4[1] = = 168:
            return False
        Default:
            return True
        }
    }
    return False
}
IP address string to int




Func Inet_aton (IPNR net. IP) Int64 {
    bits: = Strings. Split (IPNR. String (), ".")

    B0, _: = StrConv. Atoi (Bits[0])
    B1, _: = StrConv. Atoi (bits[1])
    B2, _: = StrConv. Atoi (bits[2])
    B3, _: = StrConv. Atoi (bits[3])

    var sum int64

    sum + = Int64 (b0) <<
    sum + = Int64 (B1) <<
    sum + = Int64 (b2) < ;< 8
    sum + = Int64 (b3)

    return sum
}
IP Address int to string




Func Inet_ntoa (IPNR Int64) net. IP {
    var bytes [4]byte
    bytes[0] = Byte (Ipnr & 0xFF)
    bytes[1] = Byte ((IPNR >> 8) & 0xFF)
    BYTES[2] = Byte ((ipnr >>) & 0xFF)
    bytes[3] = Byte ((ipnr >>) & 0xFF)

    return net. IPV4 (Bytes[3], bytes[2], bytes[1], bytes[0])
}
determine the IP address range




Func Ipbetween (from net. IP, to net. IP, test net. IP) bool {
    if from = = Nil | | to = NIL | | test = nil {
        FMT. PRINTLN ("An IP input is nil")//or return to an error!?
        return False
    }

    from16: = from. To16 ()
    to16: = To. To16 ()
    test16: = Test. TO16 ()
    if from16 = = Nil | | to16 = NIL | | test16 = = NIL {
        FMT. PRINTLN ("An IP does not ' convert to a")//or return an error!?
        return False
    }

    if bytes. Compare (test16, FROM16) >= 0 && bytes. Compare (test16, to16) <= 0 {
        return true
    }
    return False
}
access to state operators and other information via Taobao interface based on public IP


Interface:
http://ip.taobao.com/service/getIpInfo.php?ip=






Type ipinfo struct {
    code int ' JSON: ' Code ' '
    data IP  ' JSON: ' Data '
}

type IP struct {
    country   string ' JSON: ' Country
    ' Countryid string ' JSON: ' country_id ' area      string ' JSON: ' area ' '
    areaid    string ' JSON: ' area_id '
    region    string ' JSON: ' Region ' '
    regionid  string ' JSON: ' region_id ' '
    City      string ' JSON : "City" '
    Cityid    string ' JSON: "city_id" '
    ISP       string ' JSON: "ISP" '
}

func Tabaoapi (IP String) *ipinfo {
    URL: = "http://ip.taobao.com/service/getIpInfo.php?ip="
    url + = IP

    resp, err: = http. Get (URL)
    If err! = Nil {
        return nil
    }
    defer resp. Body.close () out

    , err: = Ioutil. ReadAll (resp. Body)
    If err! = Nil {
        return nil
    }
    var result ipinfo
    If err: = json. Unmarshal (out, &result); Err! = Nil {
        return nil
    }

    return &result
}
Full Code




package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net"
    "net/http"
    "os"
    "strconv"
    "strings"
)

type IPInfo struct {
    Code int `json:"code"`
    Data IP  `json:"data`
}

type IP struct {
    Country   string `json:"country"`
    CountryId string `json:"country_id"`
    Area      string `json:"area"`
    AreaId    string `json:"area_id"`
    Region    string `json:"region"`
    RegionId  string `json:"region_id"`
    City      string `json:"city"`
    CityId    string `json:"city_id"`
    Isp       string `json:"isp"`
}

func main() {

    external_ip := get_external()

    external_ip = strings.Replace(external_ip, "\n", "", -1)
    fmt.Println("The public IP is: ", external_ip)

     fmt.Println ("------ Dividing Line ------")

     ip: = net.ParseIP (external_ip)
     if ip == nil {
         fmt.Println ("The IP you entered is not a valid IP address, please re-enter!")
     } else {
         result: = TabaoAPI (string (external_ip))
         if result! = nil {
             fmt.Println ("Country:", result.Data.Country)
             fmt.Println ("Area:", result.Data.Area)
             fmt.Println ("City:", result.Data.City)
             fmt.Println ("Operator:", result.Data.Isp)
         }

    }

    fmt.Println("------Dividing Line------")

    GetIntranetIp()

    fmt.Println("------Dividing Line------")

    ip_int := inet_aton(net.ParseIP(external_ip))
    fmt.Println("Convert IPv4 address to decimal number(base 10) :", ip_int)

    ip_result := inet_ntoa(ip_int)
    fmt.Println("Convert decimal number(base 10) to IPv4 address:", ip_result)

    fmt.Println("------Dividing Line------")

    is_between := IpBetween(net.ParseIP("0.0.0.0"), net.ParseIP("255.255.255.255"), net.ParseIP(external_ip))
    fmt.Println("check result: ", is_between)

    fmt.Println("------Dividing Line------")
    is_public_ip := IsPublicIP(net.ParseIP(external_ip))
    fmt.Println("It is public ip: ", is_public_ip)

    is_public_ip = IsPublicIP(net.ParseIP("169.254.85.131"))
    fmt.Println("It is public ip: ", is_public_ip)

    fmt.Println("------Dividing Line------")
    fmt.Println(GetPulicIP())
}

func get_external() string {
    resp, err := http.Get("http://myexternalip.com/raw")
    if err != nil {
        return ""
    }
    defer resp.Body.Close()
    content, _ := ioutil.ReadAll(resp.Body)
    buf := new(bytes.Buffer)
    buf.ReadFrom(resp.Body)
    //s := buf.String()
    return string(content)
}

func GetIntranetIp() {
    addrs, err := net.InterfaceAddrs()

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    for _, address := range addrs {

        // Check the ip address to determine whether the loopback address if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
            if ipnet.IP.To4() != nil {
                fmt.Println("ip:", ipnet.IP.String())
            }

        }
    }
}

func TabaoAPI(ip string) *IPInfo {
    url := "http://ip.taobao.com/service/getIpInfo.php?ip="
    url += ip

    resp, err := http.Get(url)
    if err != nil {
        return nil
    }
    defer resp.Body.Close()

    out, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil
    }
    var result IPInfo
    if err := json.Unmarshal(out, &result); err != nil {
        return nil
    }

    return &result
}

func inet_ntoa(ipnr int64) net.IP {
    var bytes [4]byte
    bytes[0] = byte(ipnr & 0xFF)
    bytes[1] = byte((ipnr >> 8) & 0xFF)
    bytes[2] = byte((ipnr >> 16) & 0xFF)
    bytes[3] = byte((ipnr >> 24) & 0xFF)

    return net.IPv4(bytes[3], bytes[2], bytes[1], bytes[0])
}

func inet_aton(ipnr net.IP) int64 {
    bits := strings.Split(ipnr.String(), ".")

    b0, _ := strconv.Atoi(bits[0])
    b1, _ := strconv.Atoi(bits[1])
    b2, _ := strconv.Atoi(bits[2])
    b3, _ := strconv.Atoi(bits[3])

    var sum int64

    sum += int64(b0) << 24
    sum += int64(b1) << 16
    sum += int64(b2) << 8
    sum += int64(b3)

    return sum
}

func IpBetween(from net.IP, to net.IP, test net.IP) bool {
    if from == nil || to == nil || test == nil {
        fmt.Println("An ip input is nil") // or return an error!?
        return false
    }

    from16 := from.To16()
    to16 := to.To16()
    test16 := test.To16()
    if from16 == nil || to16 == nil || test16 == nil {
        fmt.Println("An ip did not convert to a 16 byte") // or return an error!?
        return false
    }

    if bytes.Compare(test16, from16) >= 0 && bytes.Compare(test16, to16) <= 0 {
        return true
    }
    return false
}

func IsPublicIP(IP net.IP) bool {
    if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
        return false
    }
    if ip4 := IP.To4(); ip4 != nil {
        switch true {
        case ip4[0] == 10:
            return false
        case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
            return false
        case ip4[0] == 192 && ip4[1] == 168:
            return false
        default:
            return true
        }
    }
    return false
}

func GetPulicIP() string {
    conn, _ := net.Dial("udp", "8.8.8.8:80")
    defer conn.Close()
    localAddr := conn.LocalAddr().String()
    idx := strings.LastIndex(localAddr, ":")
    return localAddr[0:idx]
}


Output:






Public network IP is:  222.128.17*.***
------Dividing line------
Country: China
: North
City: Beijing
operator: Unicom
------ Dividing line------
ip:169.254.85.131
ip:169.254.64.29
ip:169.254.211.178
ip:192.168.106.1
ip:192.168.154.1
ip:169.254.212.223
ip:192.168.10.26
ip:169.254.63.20
------Dividing Line------
Convert IPv4 Address to decimal number (base): 373297****
Convert decimal number (base) to IPv4 address:222.128.17*.***
------Dividing line------
Check Result:  true
------dividing Line------
It was public IP:  true
it was public IP:  false
------dividing line------
192.168.10.26




Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.