My task is to send a packet to 254.0.0.251 and get a response from another IP but to the same port from which it sent the request. This simple code works great in the simulator:
import UIKit
import Network
class ViewController: UIViewController {
var connection: NWConnection?
var listener: NWListener?
let host: NWEndpoint.Host = "224.0.0.251"
let port: NWEndpoint.Port = 5353
var myport: NWEndpoint.Port = 0
let params_out = NWParameters.udp
let params_in = NWParameters.udp
override func viewDidLoad() {
super.viewDidLoad()
params_out.allowLocalEndpointReuse = true
params_in.allowLocalEndpointReuse = true
connection = NWConnection(host: host, port: port, using: params_out)
connection?.stateUpdateHandler = onStateDidChange(to:)
connection?.viabilityUpdateHandler = viabilityUpdateHandler(to:)
connection?.start(queue: .global())
}
func portForEndpoint(_ endpoint: NWEndpoint) -> NWEndpoint.Port? {
switch endpoint {
case .hostPort(_, let port):
return port
default:
return nil
}
}
func onStateDidChange(to state: NWConnection.State){
switch (state) {
case .preparing:
print("Connection state: preparing")
case .ready:
print("Connection state: ready")
case .setup:
print("Connection state: setup")
case .cancelled:
print("Connection state: cancelled")
case .waiting:
print("Connection state: waiting")
case .failed:
print("Connection state: failed")
default:
print("Connection an unknown state")
}
}
func viabilityUpdateHandler(to state: Bool){
if (state) {
NSLog("Connection is viable")
myport = portForEndpoint((connection?.currentPath?.localEndpoint)!)!
print(String(describing: myport))
server()
} else {
NSLog("Connection is not viable")
}
}
func server(){
do {
listener = try NWListener(using: params_in, on: myport)
} catch {
print("exception upon creating listener")
}
listener?.stateUpdateHandler = {(newState) in
print("server: \(newState)")
switch newState {
case .ready:
print("listener ready")
default:
break
}
}
listener?.newConnectionHandler = {(newConnection) in
newConnection.stateUpdateHandler = {newState in
print("server1_: \(newState)")
switch newState {
case .ready:
print("ready")
self.receiveMessage(connection: newConnection)
default:
break
}
}
print("Connection")
newConnection.start(queue: DispatchQueue(label: "newconn"))
}
listener?.start(queue: .global())
}
func receiveMessage(connection: NWConnection) {
connection.receiveMessage { (data, context, isComplete, error) in
if(data?.count ?? 0 > 0){
print("Connection receiveMessage message: \(String(describing: data!.count))")
}
self.receiveMessage(connection: connection)
}
}
}
But on iPhone IOS 15.4.1, the error is:
[] nw_path_evaluator_evaluate NECP_CLIENT_ACTION_ADD error [48: Address already in use]
What did I do wrong or not do? Thanks for any help! Alex