Post not yet marked as solved
Post marked as unsolved with 13 replies, 1,777 views
Hey! I have been trying the last few days to discover devices in my network using NWConnection and NWConnectionGroup by sending a SSDP packet to 239.255.255.250 on port 1900 (by definition of SSDP?). I already have the multicast entitlement but that made no difference. Here are the two approaches I have tried:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
let params: NWParameters = .udp
params.allowLocalEndpointReuse = true
let connection = NWConnection(host: "239.255.255.250", port: 1_900, using: params)
connection.stateUpdateHandler = { [weak viewController = self] state in
guard let viewController = viewController else {
return
}
switch state {
case .ready:
viewController.send(to: connection)
default: return
}
}
connection.receiveMessage { (data, context, isComplete, errir) in
if let data = data {
let dataString = String(data: data, encoding: .utf8)
print(dataString ?? "", isComplete)
} else {
print(data ?? "", isComplete)
}
}
connection.start(queue: .main)
}
private func send(to connection: NWConnection) {
let message = "M-SEARCH * HTTP/1.1\r\nSt: ssdp:all\r\nHost: 239.255.255.250:1900\r\nMan: \"ssdp:discover\"\r\nMx: 1\r\n\r\n"
let payload = message.data(using: .utf8)
connection.send(content: payload, completion: .contentProcessed { (error) in
if let error = error {
print(error.localizedDescription)
} else {
print("ok")
}
})
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
do {
try setupConnection()
} catch {
print(error.localizedDescription)
}
}
private func setupConnection() throws {
let endpoints: [NWEndpoint] = [
.hostPort(host: "239.255.255.250", port: 1_900)
]
let params: NWParameters = .udp
params.allowLocalEndpointReuse = true
let multicast = try NWMulticastGroup(for: endpoints)
let group = NWConnectionGroup(with: multicast, using: params)
group.setReceiveHandler { (message, data, isComplete) in
if let data = data {
let dataString = String(data: data, encoding: .utf8)
print(message, dataString ?? "", isComplete)
} else {
print(message, data ?? "", isComplete)
}
}
group.stateUpdateHandler = { [weak viewController = self] (state) in
guard let viewController = viewController else {
return
}
switch state {
case .ready:
viewController.send(to: group)
default: return
}
}
group.start(queue: .main)
}
private func send(to group: NWConnectionGroup) {
let message = "M-SEARCH * HTTP/1.1\r\nST: ssdp:all\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\n\r\n"
let payload = message.data(using: .utf8)
group.send(content: payload) { error in
if let error = error {
print(error.localizedDescription)
} else {
print("ok")
}
}
}
}
I hope to get some help here as I couldn't find any working examples online. Thanks in advance!