How to get the address of the current machine?

The following are local IP addresses:

package main

import (
    "fmt"
    "net"
)

func main() {
    a, _ := net.LookupHost("localhost")
    fmt.Printf("Addresses: %#+v\n",a)
}

How do you usually get a local IP address by manually filtering the slice according to your needs?

+4
source share
4 answers

Here's a quick and dirty code snippet modification originally published by Russ Cox for the google-guts google group :

package main

import (
  "fmt" 
  "net" 
  "os"  
)

func main() {
  tt, err := net.Interfaces()
  if err != nil { 
    panic(err)  
  }     
  for _, t := range tt {
    aa, err := t.Addrs()
    if err != nil {
      panic(err)        
    }           
    for _, a := range aa {
      ipnet, ok := a.(*net.IPNet) 
      if !ok {          
        continue                
      }                 
      v4 := ipnet.IP.To4() 
      if v4 == nil || v4[0] == 127 { // loopback address
        continue                
      }                 
      fmt.Printf("%v\n", v4)
    }           
    os.Exit(0)  
  }     
  os.Exit(1)

}
+3
source

I have one addition: the current solutions shown above do not work, at least on FreeBSD 10, because the system returns addresses as a CIDR designation, for example. 192.168.1.2/32! Therefore, you need to slightly change the solution:

package main

import (
    "fmt"
    "net"
    "os"
    "strings"
)

func main() {
    addrs, err := net.InterfaceAddrs()
    if err != nil {
        fmt.Println("Error: " + err.Error())
        os.Exit(1)
    }

    for _, a := range addrs {
        text := a.String()

        if strings.Contains(text, `/`) {
            text = text[:strings.Index(text, `/`)]
        }

        ip := net.ParseIP(text)
        if !ip.IsLoopback() && !ip.IsUnspecified() {
            fmt.Println(ip)
        }
    }
}

Part...

if strings.Contains(text, `/`) {
    text = text[:strings.Index(text, `/`)]
}

... detects that / is part of the address and removes this part!

Yours faithfully,

Thorsten

+1

:

package main

import (
    "fmt"
    "net"
    "os"
)

func myip() {
    os.Stdout.WriteString("myip:\n")

    addrs, err := net.InterfaceAddrs()
    if err != nil {
        fmt.Errorf("error: %v\n", err.Error())
        return
    }

    for _, a := range addrs {
        ip := net.ParseIP(a.String())
        fmt.Printf("addr: %v loopback=%v\n", a, ip.IsLoopback())
    }

    fmt.Println()
}

func myip2() {
    os.Stdout.WriteString("myip2:\n")

    tt, err := net.Interfaces()
    if err != nil {
        fmt.Errorf("error: %v\n", err.Error())
        return
    }
    for _, t := range tt {
        aa, err := t.Addrs()
        if err != nil {
            fmt.Errorf("error: %v\n", err.Error())
            continue
        }
        for _, a := range aa {
            ip := net.ParseIP(a.String())
            fmt.Printf("%v addr: %v loopback=%v\n", t.Name, a, ip.IsLoopback())
        }
    }

    fmt.Println()
}

func main() {
    fmt.Println("myip -- begin")
    myip()
    myip2()
    fmt.Println("myip -- end")
}
0

Finding the right IP address can be a problem, since a typical server and development machine can have multiple interfaces. For example, $ifconfigon my Mac it returns the following interfaceslo0, gif0, stf0, en0, en1, en2, bridge0, p2p0, vmnet1, vmnet8, tap0, fw0, en4

Basically, you need to know your environment.

This is not very, but what it costs for is what I use on the Ubuntu server. He is also working on my development of Mac 10.9.2, which knows what it does on Windows.

package main

import (
    "net"
    "strings"
)

func findIPAddress() string {
    if interfaces, err := net.Interfaces(); err == nil {
        for _, interfac := range interfaces {
            if interfac.HardwareAddr.String() != "" {
                if strings.Index(interfac.Name, "en") == 0 ||
                    strings.Index(interfac.Name, "eth") == 0 {
                    if addrs, err := interfac.Addrs(); err == nil {
                        for _, addr := range addrs {
                            if addr.Network() == "ip+net" {
                                pr := strings.Split(addr.String(), "/")
                                if len(pr) == 2 && len(strings.Split(pr[0], ".")) == 4 {
                                    return pr[0]
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return ""
}

func main() {
    println(findIPAddress())
}
0
source

Source: https://habr.com/ru/post/1535499/


All Articles