Skip to content

Instantly share code, notes, and snippets.

@Cellane
Created March 22, 2016 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cellane/6f6ad58791b42926f04a to your computer and use it in GitHub Desktop.
Save Cellane/6f6ad58791b42926f04a to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
class Bonjour: NSObject, NSNetServiceDelegate, NSNetServiceBrowserDelegate {
let browser: NSNetServiceBrowser
var services: [NSNetService]
override init() {
browser = NSNetServiceBrowser()
services = [NSNetService]()
super.init()
browser.delegate = self
browser.searchForServicesOfType("_http._tcp.", inDomain: "")
}
func update() {
for service in services {
service.delegate = self
service.resolveWithTimeout(3)
}
}
func netServiceBrowser(browser: NSNetServiceBrowser, didFindService service: NSNetService, moreComing: Bool) {
print("Service appeared: \(service)")
services.append(service)
if !moreComing {
update()
}
}
func netServiceBrowser(browser: NSNetServiceBrowser, didRemoveService service: NSNetService, moreComing: Bool) {
print("Service removed: \(service)")
if let index = services.indexOf(service) {
services.removeAtIndex(index)
if !moreComing {
update()
}
}
}
func netServiceDidResolveAddress(sender: NSNetService) {
print("Service resolved: \(sender)")
print("Service port: \(sender.port)")
for addressBytes in sender.addresses! {
var storage = sockaddr()
addressBytes.getBytes(&storage, length: sizeof(sockaddr))
var address: String?
if Int32(storage.sa_family) == AF_INET {
var addr = withUnsafePointer(&storage) { UnsafePointer<sockaddr_in>($0).memory }
var addressCString = [CChar](count: Int(INET_ADDRSTRLEN), repeatedValue: 0)
inet_ntop(Int32(addr.sin_family), &addr.sin_addr, &addressCString, UInt32(INET_ADDRSTRLEN))
address = String.fromCString(addressCString)
} else if Int32(storage.sa_family) == AF_INET6 {
var addr = withUnsafePointer(&storage) { UnsafePointer<sockaddr_in6>($0).memory }
var addressCString = [CChar](count: Int(INET6_ADDRSTRLEN), repeatedValue: 0)
inet_ntop(Int32(addr.sin6_family), &addr.sin6_addr, &addressCString, UInt32(INET6_ADDRSTRLEN))
address = String.fromCString(addressCString)
}
if let address = address {
print("Address resolved: \(address)")
} else {
print("Couldn't resolve address")
}
}
}
}
let instance = Bonjour()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment