github.com/mfpierre/corectl@v0.5.6/uuid2ip/uuid2ip.go (about) 1 // Copyright 2015 - António Meireles <antonio.meireles@reformi.st> 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 16 // Package uuid2ip is a simple interface to interact with xhyve's networking 17 package uuid2ip 18 19 /* 20 #cgo CFLAGS: -framework Hypervisor -framework vmnet 21 #cgo LDFLAGS: -framework Hypervisor -framework vmnet 22 #include <stdlib.h> 23 #include "uuid2ip.c" 24 */ 25 import "C" 26 import ( 27 "fmt" 28 "io/ioutil" 29 "net" 30 "os" 31 "regexp" 32 "strings" 33 "unsafe" 34 ) 35 36 // GuestMACfromUUID returns the MAC address that will assembled from the given 37 // UUID by xhyve, needs to be called before xhyve actual invocation 38 func GuestMACfromUUID(uuid string) (mac string, err error) { 39 var ( 40 hw net.HardwareAddr 41 uuidC = C.CString(uuid) 42 ) 43 mac = C.GoString(C.vmnet_get_mac_address_from_uuid(uuidC)) 44 C.free(unsafe.Pointer(uuidC)) 45 if mac == "" { 46 err = fmt.Errorf("Could not get a MAC address from %s", uuid) 47 } else if hw, err = net.ParseMAC(mac); err == nil { 48 mac = hw.String() 49 } 50 return 51 } 52 53 // GuestIPfromMAC returns the IP address that would be leased to the given MAC 54 // address by xhyve, to be called after actual xhyve invocation 55 func GuestIPfromMAC(mac string) (ip string, err error) { 56 var ( 57 f *os.File 58 allLeases []byte 59 lastFound string 60 leasesPath = "/var/db/dhcpd_leases" 61 ipAddrRe = regexp.MustCompile(`^.*ip_address=(.+?)$`) 62 macAddrRe = regexp.MustCompile(`^.*hw_address=1,(.+?)$`) 63 ) 64 65 if f, err = os.Open(leasesPath); err != nil { 66 return 67 } 68 defer f.Close() 69 70 if allLeases, err = ioutil.ReadAll(f); err != nil { 71 return 72 } 73 74 for _, l := range strings.Split(string(allLeases), "\n") { 75 l = strings.TrimRight(l, "\r") 76 77 matches := ipAddrRe.FindStringSubmatch(l) 78 if matches != nil { 79 lastFound = matches[1] 80 continue 81 } 82 83 matches = macAddrRe.FindStringSubmatch(l) 84 // OSX's dhcp stores technically incorrect mac addr as it strips 85 // leading zeros from them, so we need to take that in consideration 86 // before checking match... 87 if matches != nil && strings.EqualFold(matches[1], 88 strings.TrimPrefix(strings.Replace(mac, ":0", ":", -1), "0")) { 89 return lastFound, nil 90 } 91 } 92 return ip, fmt.Errorf("%s isn't in ANY active DHCP lease (!)", mac) 93 }