Skip to content

Instantly share code, notes, and snippets.

@stakes
Created May 26, 2016 04:38
Show Gist options
  • Save stakes/9e7725f61674d320fba98342adc2cd35 to your computer and use it in GitHub Desktop.
Save stakes/9e7725f61674d320fba98342adc2cd35 to your computer and use it in GitHub Desktop.
//
// FramerFinder.swift
// fridge
//
// Created by Jay Stakelon on 1/1/16.
//
//
import Foundation
class FramerFinder : NSObject {
struct NetInfo {
let ip: String
let netmask: String
}
func findFramerServer() -> String {
var serverPath:String?
serverPath = getMyIP()
return serverPath!
}
// Get the local ip addresses used by this node
func getMyIP() -> String {
// var addresses = [NetInfo]()
var ipaddress = String()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0 {
// For each interface ...
for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) {
let flags = Int32(ptr.memory.ifa_flags)
var addr = ptr.memory.ifa_addr.memory
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
// Convert interface address to a human readable string:
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST) == 0) {
if let address = String.fromCString(hostname) {
var net = ptr.memory.ifa_netmask.memory
var netmaskName = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
getnameinfo(&net, socklen_t(net.sa_len), &netmaskName, socklen_t(netmaskName.count),
nil, socklen_t(0), NI_NUMERICHOST) == 0
if let _ = String.fromCString(netmaskName) {
// addresses.append(NetInfo(ip: address, netmask: netmask))
ipaddress = address
}
}
}
}
}
}
freeifaddrs(ifaddr)
}
return ipaddress
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment