本文整理匯總了Golang中net.IP.String方法的典型用法代碼示例。如果您正苦於以下問題:Golang IP.String方法的具體用法?Golang IP.String怎麽用?Golang IP.String使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類net.IP
的用法示例。
在下文中一共展示了IP.String方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: RequestPort
// RequestPort requests new port from global ports pool for specified ip and proto.
// If port is 0 it returns first free port. Otherwise it cheks port availability
// in pool and return that port or error if port is already busy.
func RequestPort(ip net.IP, proto string, port int) (int, error) {
mutex.Lock()
defer mutex.Unlock()
if proto != "tcp" && proto != "udp" {
return 0, ErrUnknownProtocol
}
if ip == nil {
ip = defaultIP
}
ipstr := ip.String()
protomap, ok := globalMap[ipstr]
if !ok {
protomap = newProtoMap()
globalMap[ipstr] = protomap
}
mapping := protomap[proto]
if port > 0 {
if _, ok := mapping.p[port]; !ok {
mapping.p[port] = struct{}{}
return port, nil
}
return 0, NewErrPortAlreadyAllocated(ipstr, port)
}
port, err := mapping.findPort()
if err != nil {
return 0, err
}
return port, nil
}
示例2: deleteSvcRecords
func (n *network) deleteSvcRecords(name string, epIP net.IP, ipMapUpdate bool) {
c := n.getController()
c.Lock()
defer c.Unlock()
sr, ok := c.svcDb[n.ID()]
if !ok {
return
}
if ipMapUpdate {
delete(sr.ipMap, netutils.ReverseIP(epIP.String()))
}
ipList := sr.svcMap[name]
for i, ip := range ipList {
if ip.Equal(epIP) {
ipList = append(ipList[:i], ipList[i+1:]...)
break
}
}
sr.svcMap[name] = ipList
if len(ipList) == 0 {
delete(sr.svcMap, name)
}
}
示例3: NodeAddresses
// NodeAddresses returns the NodeAddresses of the instance with the specified nodeName.
func (v *OVirtCloud) NodeAddresses(nodeName types.NodeName) ([]api.NodeAddress, error) {
name := mapNodeNameToInstanceName(nodeName)
instance, err := v.fetchInstance(name)
if err != nil {
return nil, err
}
var address net.IP
if instance.IPAddress != "" {
address = net.ParseIP(instance.IPAddress)
if address == nil {
return nil, fmt.Errorf("couldn't parse address: %s", instance.IPAddress)
}
} else {
resolved, err := net.LookupIP(name)
if err != nil || len(resolved) < 1 {
return nil, fmt.Errorf("couldn't lookup address: %s", name)
}
address = resolved[0]
}
return []api.NodeAddress{
{Type: api.NodeLegacyHostIP, Address: address.String()},
{Type: api.NodeInternalIP, Address: address.String()},
{Type: api.NodeExternalIP, Address: address.String()},
}, nil
}
示例4: findLoopbackDevice
// findLoopbackDevice iterates through all the interfaces on a machine and
// returns the ip addr, mask of the loopback device
func (a *Agent) findLoopbackDevice() (string, string, string, error) {
var ifcs []net.Interface
var err error
ifcs, err = net.Interfaces()
if err != nil {
return "", "", "", err
}
for _, ifc := range ifcs {
addrs, err := ifc.Addrs()
if err != nil {
return "", "", "", err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip.IsLoopback() {
if ip.To4() == nil {
continue
}
return ifc.Name, ip.String(), addr.String(), nil
}
}
}
return "", "", "", fmt.Errorf("no loopback devices with IPV4 addr found")
}
示例5: interfaceGot
func interfaceGot(index int, pciAddr int, name string, inf *network.Settings) (*InterfaceCreated, error) {
ip, nw, err := net.ParseCIDR(fmt.Sprintf("%s/%d", inf.IPAddress, inf.IPPrefixLen))
if err != nil {
glog.Error("can not parse cidr")
return &InterfaceCreated{Index: index, PCIAddr: pciAddr, DeviceName: name}, err
}
var tmp []byte = nw.Mask
var mask net.IP = tmp
rt := []*RouteRule{}
/* Route rule is generated automaticly on first interface,
* or generated on the gateway configured interface. */
if (index == 0 && inf.Automatic) || (!inf.Automatic && inf.Gateway != "") {
rt = append(rt, &RouteRule{
Destination: "0.0.0.0/0",
Gateway: inf.Gateway, ViaThis: true,
})
}
return &InterfaceCreated{
Index: index,
PCIAddr: pciAddr,
Bridge: inf.Bridge,
HostDevice: inf.Device,
DeviceName: name,
Fd: inf.File,
MacAddr: inf.Mac,
IpAddr: ip.String(),
NetMask: mask.String(),
RouteTable: rt,
}, nil
}
示例6: Allocate
// Allocate a network interface
func Allocate(job *engine.Job) engine.Status {
var (
ip *net.IP
err error
id = job.Args[0]
requestedIP = net.ParseIP(job.Getenv("RequestedIP"))
)
if requestedIP != nil {
ip, err = ipallocator.RequestIP(bridgeNetwork, &requestedIP)
} else {
ip, err = ipallocator.RequestIP(bridgeNetwork, nil)
}
if err != nil {
return job.Error(err)
}
out := engine.Env{}
out.Set("IP", ip.String())
out.Set("Mask", bridgeNetwork.Mask.String())
out.Set("Gateway", bridgeNetwork.IP.String())
out.Set("Bridge", bridgeIface)
size, _ := bridgeNetwork.Mask.Size()
out.SetInt("IPPrefixLen", size)
currentInterfaces.Set(id, &networkInterface{
IP: *ip,
})
out.WriteTo(job.Stdout)
return engine.StatusOK
}
示例7: iptablesCommonPortalArgs
// Build a slice of iptables args that are common to from-container and from-host portal rules.
func iptablesCommonPortalArgs(destIP net.IP, addPhysicalInterfaceMatch bool, addDstLocalMatch bool, destPort int, protocol api.Protocol, service proxy.ServicePortName) []string {
// This list needs to include all fields as they are eventually spit out
// by iptables-save. This is because some systems do not support the
// 'iptables -C' arg, and so fall back on parsing iptables-save output.
// If this does not match, it will not pass the check. For example:
// adding the /32 on the destination IP arg is not strictly required,
// but causes this list to not match the final iptables-save output.
// This is fragile and I hope one day we can stop supporting such old
// iptables versions.
args := []string{
"-m", "comment",
"--comment", service.String(),
"-p", strings.ToLower(string(protocol)),
"-m", strings.ToLower(string(protocol)),
"--dport", fmt.Sprintf("%d", destPort),
}
if destIP != nil {
args = append(args, "-d", fmt.Sprintf("%s/32", destIP.String()))
}
if addPhysicalInterfaceMatch {
args = append(args, "-m", "physdev", "!", "--physdev-is-in")
}
if addDstLocalMatch {
args = append(args, "-m", "addrtype", "--dst-type", "LOCAL")
}
return args
}
示例8: resolvePeer
func (d *driver) resolvePeer(nid string, peerIP net.IP) (net.HardwareAddr, net.IPMask, net.IP, error) {
qPayload := fmt.Sprintf("%s %s", string(nid), peerIP.String())
resp, err := d.serfInstance.Query("peerlookup", []byte(qPayload), nil)
if err != nil {
return nil, nil, nil, fmt.Errorf("resolving peer by querying the cluster failed: %v", err)
}
respCh := resp.ResponseCh()
select {
case r := <-respCh:
var macStr, maskStr, vtepStr string
if _, err := fmt.Sscan(string(r.Payload), &macStr, &maskStr, &vtepStr); err != nil {
return nil, nil, nil, fmt.Errorf("bad response %q for the resolve query: %v", string(r.Payload), err)
}
mac, err := net.ParseMAC(macStr)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to parse mac: %v", err)
}
return mac, net.IPMask(net.ParseIP(maskStr).To4()), net.ParseIP(vtepStr), nil
case <-time.After(time.Second):
return nil, nil, nil, fmt.Errorf("timed out resolving peer by querying the cluster")
}
}
示例9: GetIfacesByIP
// GetIfacesByIP searches for and returns the interfaces with the given IP
// Disregards the subnet mask since not every net.IP object contains
// On success it will return the list of found interfaces
func (n *Networking) GetIfacesByIP(ifaceIP net.IP) ([]net.Interface, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
searchAddr := strings.Split(ifaceIP.String(), "/")[0]
resultInterfaces := make([]net.Interface, 0)
for _, iface := range ifaces {
if iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, err := iface.Addrs()
if err != nil {
return nil, errwrap.Wrap(fmt.Errorf("cannot get addresses for interface %v", iface.Name), err)
}
for _, addr := range addrs {
currentAddr := strings.Split(addr.String(), "/")[0]
if searchAddr == currentAddr {
resultInterfaces = append(resultInterfaces, iface)
break
}
}
}
if len(resultInterfaces) == 0 {
return nil, fmt.Errorf("no interface found with IP %q", ifaceIP)
}
return resultInterfaces, nil
}
示例10: get_ips
func get_ips() ([]string, error) {
ips := make([]string, 0)
ifaces, err := net.Interfaces()
if err != nil {
log.Println(err)
return ips, nil
}
for _, iface := range ifaces {
// log.Println(iface.Name)
addrs, err := iface.Addrs()
if err != nil {
return ips, nil
}
for _, addr := range addrs {
// log.Println(addr.Network(), addr.String())
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
// 隻保留ipv4地址
if ip.To4() != nil && ip.String() != "127.0.0.1" {
ips = append(ips, ip.String())
}
}
}
return ips, nil
}
示例11: lookup
func lookup(stmt *sql.Stmt, IP net.IP, nIP uint32) (*GeoIP, error) {
var reserved bool
for _, net := range reservedIPs {
if net.Contains(IP) {
reserved = true
break
}
}
geoip := GeoIP{Ip: IP.String()}
if reserved {
geoip.CountryCode = "RD"
geoip.CountryName = "Reserved"
} else {
if err := stmt.QueryRow(nIP).Scan(
&geoip.CountryCode,
&geoip.CountryName,
&geoip.RegionCode,
&geoip.RegionName,
&geoip.CityName,
&geoip.ZipCode,
&geoip.Latitude,
&geoip.Longitude,
&geoip.MetroCode,
&geoip.AreaCode,
); err != nil {
return nil, err
}
}
return &geoip, nil
}
示例12: Request
// Request answers a dhcp request
// Uses etcd as backend
// part of DHCPDataSource interface implementation
func (ds *EtcdDataSource) Request(nic string, currentIP net.IP) (net.IP, error) {
ds.lockDHCPAssign()
defer ds.unlockdhcpAssign()
machines, _ := ds.Machines()
macExists, ipExists := false, false
for _, node := range machines {
thisNodeIP, _ := node.IP()
ipMatch := thisNodeIP.String() == currentIP.String()
macMatch := nic == node.Mac().String()
if ipMatch && macMatch {
ds.store(node, thisNodeIP)
return currentIP, nil
}
ipExists = ipExists || ipMatch
macExists = macExists || macMatch
}
if ipExists || macExists {
return nil, errors.New("Missmatch in lease pool")
}
macAddress, _ := net.ParseMAC(nic)
ds.CreateMachine(macAddress, currentIP)
return currentIP, nil
}
示例13: addSvcRecords
func (n *network) addSvcRecords(name string, epIP net.IP, ipMapUpdate bool) {
c := n.getController()
c.Lock()
defer c.Unlock()
sr, ok := c.svcDb[n.ID()]
if !ok {
sr = svcInfo{
svcMap: make(map[string][]net.IP),
ipMap: make(map[string]string),
}
c.svcDb[n.ID()] = sr
}
if ipMapUpdate {
reverseIP := netutils.ReverseIP(epIP.String())
if _, ok := sr.ipMap[reverseIP]; !ok {
sr.ipMap[reverseIP] = name
}
}
ipList := sr.svcMap[name]
for _, ip := range ipList {
if ip.Equal(epIP) {
return
}
}
sr.svcMap[name] = append(sr.svcMap[name], epIP)
}
示例14: newProxyCommand
func newProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int, proxyPath string) (userlandProxy, error) {
path := proxyPath
if proxyPath == "" {
cmd, err := exec.LookPath(userlandProxyCommandName)
if err != nil {
return nil, err
}
path = cmd
}
args := []string{
path,
"-proto", proto,
"-host-ip", hostIP.String(),
"-host-port", strconv.Itoa(hostPort),
"-container-ip", containerIP.String(),
"-container-port", strconv.Itoa(containerPort),
}
return &proxyCommand{
cmd: &exec.Cmd{
Path: path,
Args: args,
SysProcAttr: &syscall.SysProcAttr{
Pdeathsig: syscall.SIGTERM, // send a sigterm to the proxy if the daemon process dies
},
},
}, nil
}
示例15: addrsOfOneInterface
// 一個接口上的所有ip4地址
func addrsOfOneInterface(iface net.Interface) (addrs []*net.IPAddr) {
ifaddrs, err := iface.Addrs()
if (err != nil) || (len(ifaddrs) == 0) {
return
}
for _, ifaddr := range ifaddrs {
var ip net.IP
switch v := ifaddr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
default:
continue
}
if ip.IsLoopback() {
return
}
ip = ip.To4()
if ip != nil {
addr, _ := net.ResolveIPAddr("ip", ip.String())
addrs = append(addrs, addr)
}
}
return
}