本文整理匯總了Golang中net.IP類的典型用法代碼示例。如果您正苦於以下問題:Golang IP類的具體用法?Golang IP怎麽用?Golang IP使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了IP類的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: GetPrivateIP
// GetPrivateIP returns the first private IP address found in a list of
// addresses.
func GetPrivateIP(addresses []net.Addr) (net.IP, error) {
var candidates []net.IP
// Find private IPv4 address
for _, rawAddr := range addresses {
var ip net.IP
switch addr := rawAddr.(type) {
case *net.IPAddr:
ip = addr.IP
case *net.IPNet:
ip = addr.IP
default:
continue
}
if ip.To4() == nil {
continue
}
if !IsPrivateIP(ip.String()) {
continue
}
candidates = append(candidates, ip)
}
numIps := len(candidates)
switch numIps {
case 0:
return nil, fmt.Errorf("No private IP address found")
case 1:
return candidates[0], nil
default:
return nil, fmt.Errorf("Multiple private IPs found. Please configure one.")
}
}
示例4: 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
}
示例5: getDNSRecordTypeByIP
// getDNSRecordTypeByIP returns the DNS record type for the given IP.
// It will return "A" for an IPv4 address and "AAAA" for an IPv6 address.
func getDNSRecordTypeByIP(ip net.IP) string {
if ip.To4() == nil {
return "AAAA"
}
return "A"
}
示例6: IpToRadixkey
func IpToRadixkey(prefix net.IP, prefixLen uint8) string {
b := prefix.To4()
if b == nil {
b = prefix.To16()
}
return toRadixkey(b, prefixLen)
}
示例7: claimNodePort
// Marks a port as being owned by a particular service, or returns error if already claimed.
// Idempotent: reclaiming with the same owner is not an error
func (proxier *Proxier) claimNodePort(ip net.IP, port int, protocol api.Protocol, owner proxy.ServicePortName) error {
proxier.portMapMutex.Lock()
defer proxier.portMapMutex.Unlock()
// TODO: We could pre-populate some reserved ports into portMap and/or blacklist some well-known ports
key := portMapKey{ip: ip.String(), port: port, protocol: protocol}
existing, found := proxier.portMap[key]
if !found {
// Hold the actual port open, even though we use iptables to redirect
// it. This ensures that a) it's safe to take and b) that stays true.
// NOTE: We should not need to have a real listen()ing socket - bind()
// should be enough, but I can't figure out a way to e2e test without
// it. Tools like 'ss' and 'netstat' do not show sockets that are
// bind()ed but not listen()ed, and at least the default debian netcat
// has no way to avoid about 10 seconds of retries.
socket, err := newProxySocket(protocol, ip, port)
if err != nil {
return fmt.Errorf("can't open node port for %s: %v", key.String(), err)
}
proxier.portMap[key] = &portMapValue{owner: owner, socket: socket}
glog.V(2).Infof("Claimed local port %s", key.String())
return nil
}
if existing.owner == owner {
// We are idempotent
return nil
}
return fmt.Errorf("Port conflict detected on port %s. %v vs %v", key.String(), owner, existing)
}
示例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: GetLocalIP
// GetLocalIP return the first external-IP4 configured for the first
// interface connected to this node.
func GetLocalIP() (net.IP, error) {
interfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range interfaces {
if (iface.Flags & net.FlagUp) == 0 {
continue // interface down
}
if (iface.Flags & net.FlagLoopback) != 0 {
continue // loopback interface
}
addrs, err := iface.Addrs()
if err != nil {
return nil, 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 != nil && !ip.IsLoopback() {
if ip = ip.To4(); ip != nil {
return ip, nil
}
}
}
}
return nil, errors.New("cannot find local IP address")
}
示例10: GetIpWithPrefix
//
// 獲取帶有指定Prefix的Ip
//
func GetIpWithPrefix(prefix string) string {
ifaces, _ := net.Interfaces()
// handle err
for _, i := range ifaces {
addrs, _ := i.Addrs()
// handle 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
}
ipAddr := ip.String()
// fmt.Println("ipAddr: ", ipAddr)
if strings.HasPrefix(ipAddr, prefix) {
return ipAddr
}
}
}
return ""
}
示例11: 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
}
示例12: bigForIP
// bigForIP creates a big.Int based on the provided net.IP
func bigForIP(ip net.IP) *big.Int {
b := ip.To4()
if b == nil {
b = ip.To16()
}
return big.NewInt(0).SetBytes(b)
}
示例13: 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
}
示例14: validateNodeIP
// Validate given node IP belongs to the current host
func (kl *Kubelet) validateNodeIP() error {
if kl.nodeIP == nil {
return nil
}
// Honor IP limitations set in setNodeStatus()
if kl.nodeIP.IsLoopback() {
return fmt.Errorf("nodeIP can't be loopback address")
}
if kl.nodeIP.To4() == nil {
return fmt.Errorf("nodeIP must be IPv4 address")
}
addrs, err := net.InterfaceAddrs()
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 != nil && ip.Equal(kl.nodeIP) {
return nil
}
}
return fmt.Errorf("Node IP: %q not found in the host's network interfaces", kl.nodeIP.String())
}
示例15: 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
}