hello
I am testing the use of network extension. When we use dnsproxy to proxy DNS requests,
we will send you a message that the udp pcbcount of your system continues to increase.
For example
for ((i=1; i<=99999; i++));do
echo "Attempt $i:"
dig google.com
done
when the dig command is used continuously,
the dig command will show the following errors when pcbcount reaches a certain number.
isc_socket_bind: address not available
Can you help us determine what the problem might be? thank you
Networking
RSS for tagExplore the networking protocols and technologies used by the device to connect to Wi-Fi networks, Bluetooth devices, and cellular data services.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Based on threads from past years, it is mentioned that a NEFilterDataProvider supports IPPROTO_TCP, IPPROTO_UDP, IPPROTO_ICMP and IPPROTO_IGMP.
[Q] What about IPPROTO_RAW? Is this something that would have been added recently?
It is not possible to establish a point-to-point WiFi connection between iPhone models 15 and 16 (iOS 18) and the HiFlying HF-LPB100-1 module used by our IoT devices to control Yale locks: https://www.yaleconnecthub.com/en/compatible-products/hub
The message displayed on the iPhone WiFi network settings screen when selecting the HF-LPB100-1 module network states 'Unable to connect'.
It is important to highlight that all iPhone models and previous OS versions are compatible with this WiFi module (antenna + chipset).
We already made a post in the Feedback Assistence platform FB15809338 (Provisioning an IoT devise under iOS 18 - Wi-Fi incompatibility )
STEPS TO REPRODUCE
Plug in the Yale Connect Hub model YALE-4971 (with HF-LPB100-1 module) > The device's WiFi module will start reporting its network.
On an iPhone 15 or 16 -using iOS 18 - display the WiFi network configuration screen and select Yale´s device network (it is named Yale-xxxxxx).
Select the Yale network for the iPhone to connect point-to-point.
An error message will appear: Unable to connect.
I’m developing a iOS VPN app, and I need to execute a task in the main app even when it’s in the background or killed state. I know the Network Extension continues running during those times. Is there a way for the extension to immediately notify the app or trigger a task on the app side?
Hello all,
I have a question,
I am developing an application that uses the apply() function of the NEHotspotConfigurationManager class to switch the Wifi of the device.
In the completionHandler of the apply() function, the error argument contains “Internal Error(8)” and the wifi switching may fail.
We have never seen this problem during development, and since it occurs only in the market, we are at a loss as to the cause and countermeasure.
Do you know the cause of the “Internal Error(8)” and how to fix it?
A similar phenomenon has already been discussed in the following thread, but after countermeasures were taken in iOS12, it also occurs in iOS13 and later and no progress has been made since then.
https://developer.apple.com/forums/thread/107851
I would appreciate it if someone could clarify what is happening with this error, as there is not much information on the web regarding this error.
Thank you in advance.
Hello,
I have been testing my app in iOS 18 device and while creating a server with TCP, then apple make a request for local network permission automatically. If we don't allow the permission, the connection not working. We are getting the connection timeout error even after allowing again from device setting.
Has something changed in the flow for iOS 18 version? Can someone help me to solve this issue?
Hi,
I have a hardware device that asks as an ethernet server.
I need to connect to it using a TCP socket over ethernet.
Problem is, I cannot find an API or example code on how to go about this. I have tried to search through the available network interfaces using AF_LINK (link layer) family but only the wifi shows up (en0), even when the device is connected and the iPhone self-assigns an IP etc.
Extra challenge is, I am using objective C because all of my other code is written that way. I'm happy to add a swift module where that is the only option.
Can someone please point me in the right direction?
Hi everyone,
I’m developing an app called FindMyNet that allows users to find the best internet provider based on their postal code (CAP). The app is built with Xcode and the macOS simulator. I’ve set up a FastAPI backend that communicates with an Excel database containing internet provider data for each postal code.
Unfortunately, when I try to run the app, I encounter an error that prevents me from retrieving data from the database and displaying the correct provider.
Task <6B5C86B6-181A-4235-AE68-23AAF6645683>.<1> finished with error [1] Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted" UserInfo={_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <6B5C86B6-181A-4235-AE68-23AAF6645683>.<1>, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=1, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <6B5C86B6-181A-4235-AE68-23AAF6645683>.<1>" ), _NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en0[802.11], ipv4, dns, uses wifi}
Problem description:
• The FastAPI backend is running on a Raspberry Pi and communicates with the app via an HTTP request.
• When I enter a postal code, the app should return the best provider for that region, but I only get a 500 error.
• I’ve verified that the FastAPI server is running, but it seems there’s an issue with communication between the app and the server.
Steps taken so far:
• I’ve checked the logs on the FastAPI server, but there are no obvious errors.
• I’ve manually tested the API using Postman, and it works fine, so the issue seems to be app-side.
Support request:
I’d like to understand better what could be causing this error and if anyone has had similar experiences. Any advice on diagnosing the problem or solutions for resolving it would be greatly appreciated.
Thanks in advance for your help!
Topic:
App & System Services
SubTopic:
Networking
I have an issue that causes multiple instances of the push provider to be initialized. And I'd like to ask you what could trigger the instantiation NEAppPushProvider subclass. It seems like it's being triggered excessively. If there's documentation that I have overlooked then just show it to me and I'll be on my way.
Here's the details. But really all I want to know is why is my subclass for NEAppPushProvider keeps getting initialized. If you can answer me that than maybe all these details don't really matter but here they are.
Here's why I believe there's multiple push provider. I see logs for my push provider initializing but I don't see it de-initializing. I also see redundant logs showing multiple instances trying to log into my server. Each time it initializes, an additional log is added for trying to log into my server.
In the app, the system saves it's configuration shortly after initialization, after saving and loading the push configuration, the app doesn't touch config.
Meanwhile in the extension, after 8 or so hours, the extension starts creating a new instance of the push provider. Then a few hours later it does it again. And again. Until the watch dog kills us for wasting too much CPU.
Normally on a fresh install, I'll observe turning off the wifi to call stop on the push provider and later have the push provider de-initialize.
The extension maintains a socket connection to the server, the server can send it messages to display push notifications. The software runs on hospital networks, which will not have access to the internet. It seems like the connection to the server is stable from the logs. I don't detect any disconnections. I'll check with the server to confirm.
In the app I call removeFromPreferences to clear out any extensions before logging in/saving push configurations. And I call saveToPreferences on the NEAppPushManager. I do this to make sure I don't have more than one push configuration saved at one time. I also have many logs looking out for this. I used the sample code from apple as the basis of the my own Push Manager. I can post code if you deem it necessary.
Hope to here from you soon. Thank you.
Hello,
I have been implementing NEAppPushProvider class to establish my own protocol to directly communicate with our provider server without the need to rely on APNs for background push notifications.
I am at a stage where I am able to establish a tcp communicator and receive messages back and forth but I noticed that when I disconnect from the WIFI I've set up by setting a given SSID, I am not getting hit on the Stop method. Below is briefly how I load and save preferences.
NEAppPushManager appPushManager = new NEAppPushManager();
appPushManager.LoadFromPreferences((error) =>
{
if (error != null)
{
Console.WriteLine($"Error loading NEAppPushManager preferences: {error.LocalizedDescription}");
return;
}
if (!enable)
{
Console.WriteLine("Disabling Local Push Provider...");
appPushManager.Enabled = false;
// ✅ Immediately update UserDefaults before saving preferences
userDefaults.SetBool(false, Constants.IsLocalPushEnabled);
userDefaults.Synchronize();
appPushManager.SaveToPreferences((saveError) =>
{
if (saveError != null)
{
Console.WriteLine($"Error disabling Local Push: {saveError.LocalizedDescription}");
}
else
{
Console.WriteLine("Local Push successfully disabled.");
}
});
return;
}
// ✅ Now we can safely enable Local Push
Console.WriteLine($"Enabling Local Push for SSID: {_currentSSID}");
appPushManager.MatchSsids = new string[] { _currentSSID };
appPushManager.LocalizedDescription = "LocalPushProvider";
appPushManager.ProviderBundleIdentifier = Constants.LocalPushExtensionBundleId;
appPushManager.Enabled = true;
appPushManager.SaveToPreferences((saveError) =>
{
if (saveError != null)
{
Console.WriteLine($"Error saving Local Push settings: {saveError.LocalizedDescription}");
}
else
{
Console.WriteLine("✅ Local Push successfully registered.");
userDefaults.SetBool(true, Constants.IsLocalPushEnabled);
userDefaults.Synchronize();
}
});
});
I've read through documentation and was expecting the Stop method to be hit when I turn off Wifi. Am I missing anything? Please let me know if I should provide more info. Currently I just have a console writeline method inside the Stop method to see if it actually gets hit.
IMPORTANT The resume rate limiter is now covered by the official documentation. See Use background sessions efficiently within Downloading files in the background. So, the following is here purely for historical perspective.
NSURLSession’s background session support on iOS includes a resume rate limiter. This limiter exists to prevent apps from abusing the background session support in order to run continuously in the background. It works as follows:
nsurlsessiond (the daemon that does all the background session work) maintains a delay value for your app.
It doubles that delay every time it resumes (or relaunches) your app.
It resets that delay to 0 when the user brings your app to the front.
It also resets the delay to 0 if the delay period elapses without it having resumed your app.
When your app creates a new task while it is in the background, the task does not start until that delay has expired.
To understand the impact of this, consider what happens when you download 10 resources. If you pass them to the background session all at once, you see something like this:
Your app creates tasks 1 through 10 in the background session.
nsurlsessiond starts working on the first few tasks.
As tasks complete, nsurlsessiond starts working on subsequent ones.
Eventually all the tasks complete and nsurlsessiond resumes your app.
Now consider what happens if you only schedule one task at a time:
Your app creates task 1.
nsurlsessiond starts working on it.
When it completes, nsurlsessiond resumes your app.
Your app creates task 2.
nsurlsessiond delays the start of task 2 a little bit.
nsurlsessiond starts working on task 2.
When it completes, nsurlsessiond resumes your app.
Your app creates task 3.
nsurlsessiond delays the start of task 3 by double the previous amount.
nsurlsessiond starts working on task 3.
When it completes, nsurlsessiond resumes your app.
Steps 8 through 11 repeat, and each time the delay doubles. Eventually the delay gets so large that it looks like your app has stopped making progress.
If you have a lot of tasks to run then you can mitigate this problem by starting tasks in batches. That is, rather than start just one task in step 1, you would start 100. This only helps up to a point. If you have thousands of tasks to run, you will eventually start seeing serious delays. In that case it’s much better to change your design to use fewer, larger transfers.
Note All of the above applies to iOS 8 and later. Things worked differently in iOS 7. There’s a post on DevForums that explains the older approach.
Finally, keep in mind that there may be other reasons for your task not starting. Specifically, if the task is flagged as discretionary (because you set the discretionary flag when creating the task’s session or because the task was started while your app was in the background), the task may be delayed for other reasons (low power, lack of Wi-Fi, and so on).
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
(r. 22323366)
My application advertises service uuid FC66 and 00410b66-2553-48d7-cf18-000000002154 in advertising data, and "loading" as local name in response data in foreground.
But iOS cut local name to "loadi" and add Hashed UUID data 0100000000000000000000000600000000 to response data.
Why iOS add hashed uuid data? Is it because my 128-bit uuid format is wrong?
We want to advertise the complete local name data.
How to avoid this problem?
In my app I have Local Push connectivity for local push notifications. My app has proper entitlment granted by Apple and NEAppPushProvider was working perfectly on older iOS versions before iOS26.
The problem I faced with iOS26: when i enable VPN - NEAppPushProvider stops with reason
/** @const NEProviderStopReasonNoNetworkAvailable There is no network connectivity. */
case noNetworkAvailable = 3.
But device is still connected to proper SSID that is included to matchSSIDs.
I discovered it only happens if my VPN config file include this line
redirect-gateway def1
without that line NEAppPushProvider works as expected with enabled VPN.
I use OpenVPN app.
Is it a bug of iOS26 or I need some additional setup?
Please help!
This is a topic that’s come up a few times on the forums, so I thought I’d write up a summary of the issues I’m aware of. If you have questions or comments, start a new thread in the App & System Services > Networking subtopic and tag it with Network Extension. That way I’ll be sure to see it go by.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Network Extension Provider Packaging
There are two ways to package a network extension provider:
App extension ( appex )
System extension ( sysex )
Different provider types support different packaging on different platforms. See TN3134 Network Extension provider deployment for the details.
Some providers, most notably packet tunnel providers on macOS, support both appex and sysex packaging. Sysex packaging has a number of advantages:
It supports direct distribution, using Developer ID signing.
It better matches the networking stack on macOS. An appex is tied to the logged in user, whereas a sysex, and the networking stack itself, is global to the system as a whole.
Given that, it generally makes sense to package your Network Extension (NE) provider as a sysex on macOS. If you’re creating a new product that’s fine, but if you have an existing iOS product that you want to bring to macOS, you have to account for the differences brought on by the move to sysex packaging. Similarly, if you have an existing sysex product on macOS that you want to bring to iOS, you have to account for the appex packaging. This post summarises those changes.
Keep the following in mind while reading this post:
The information here applies to all NE providers that can be packaged as either an appex or a sysex. When this post uses a specific provider type in an example, it’s just an example.
Unless otherwise noted, any information about iOS also applies to iPadOS, tvOS, and visionOS.
Process Lifecycle
With appex packaging, the system typically starts a new process for each instance of your NE provider. For example, with a packet tunnel provider:
When the users starts the VPN, the system creates a process and then instantiates and starts the NE provider in that process.
When the user stops the VPN, the system stops the NE provider and then terminates the process running it.
If the user starts the VPN again, the system creates an entirely new process and instantiates and starts the NE provider in that.
In contrast, with sysex packaging there’s typically a single process that runs all off the sysex’s NE providers. Returning to the packet tunnel provider example:
When the users starts the VPN, the system instantiates and starts the NE provider in the sysex process.
When the user stops the VPN, the system stops and deallocates the NE provider instances, but leaves the sysex process running.
If the user starts the VPN again, the system instantiates and starts a new instances of the NE provider in the sysex process.
This lifecycle reflects how the system runs the NE provider, which in turn has important consequences on what the NE provider can do:
An appex acts like a launchd agent [1], in that it runs in a user context and has access to that user’s state.
A sysex is effectively a launchd daemon. It runs in a context that’s global to the system as a whole. It does not have access to any single user’s state. Indeed, there might be no user logged in, or multiple users logged in.
The rest of this post explores specific consequences of the NE provider lifecycle.
[1] It’s not actually run as a launchd agent. Rather, there’s a system launchd agent that acts as the host for the app extension.
App Groups
With an app extension, the app extension and its container app run as the same user. Thus it’s trivial to share state between them using an app group container.
Note When talking about extensions on Apple platforms, the container app is the app in which the extension is embedded and the host app is the app using the extension. For network extensions the host app is the system itself.
That’s not the case with a system extension. The system extension runs as root whereas the container app runs an the user who launched it. While both programs can claim access to the same app group, the app group container location they receive will be different. For the system extension that location will be inside the home directory for the root user. For the container app the location will be inside the home directory of the user who launched it.
This does not mean that app groups are useless in a Network Extension app. App groups are also a factor in communicating between the container app and its extensions, the subject of the next section.
IMPORTANT App groups have a long and complex history on macOS. For the full story, see App Groups: macOS vs iOS: Working Towards Harmony.
Communicating with Extensions
With an app extension there are two communication options:
App-provider messages
App groups
App-provider messages are supported by NE directly. In the container app, send a message to the provider by calling sendProviderMessage(_:responseHandler:) method. In the appex, receive that message by overriding the handleAppMessage(_:completionHandler:) method.
An appex can also implement inter-process communication (IPC) using various system IPC primitives. Both the container app and the appex claim access to the app group via the com.apple.security.application-groups entitlement. They can then set up IPC using various APIs, as explain in the documentation for that entitlement.
With a system extension the story is very different. App-provider messages are supported, but they are rarely used. Rather, most products use XPC for their communication. In the sysex, publish a named XPC endpoint by setting the NEMachServiceName property in its Info.plist. Listen for XPC connections on that endpoint using the XPC API of your choice.
Note For more information about the available XPC APIs, see XPC Resources.
In the container app, connect to that named XPC endpoint using the XPC Mach service name API. For example, with NSXPCConnection, initialise the connection with init(machServiceName:options:), passing in the string from NEMachServiceName. To maximise security, set the .privileged flag.
Note XPC Resources has a link to a post that explains why this flag is important.
If the container app is sandboxed — necessary if you ship on the Mac App Store — then the endpoint name must be prefixed by an app group ID that’s accessible to that app, lest the App Sandbox deny the connection. See app groups documentation for the specifics.
When implementing an XPC listener in your sysex, keep in mind that:
Your sysex’s named XPC endpoint is registered in the global namespace. Any process on the system can open a connection to it [1]. Your XPC listener must be prepared for this. If you want to restrict connections to just your container app, see XPC Resources for a link to a post that explains how to do that.
Your sysex only gets one named XPC endpoint, and thus one XPC listener. If your sysex includes multiple NE providers, take that into account when you design your XPC protocol.
[1] Assuming that connection isn’t blocked by some other mechanism, like the App Sandbox.
Inter-provider Communication
A sysex can include multiple types of NE providers. For example, a single sysex might include a content filter and a DNS proxy provider. In that case the system instantiates all of the NE providers in the same sysex process. These instances can communicate without using IPC, for example, by storing shared state in global variables (with suitable locking, of course).
It’s also possible for a single container app to contain multiple sysexen, each including a single NE provider. In that case the system instantiates the NE providers in separate processes, one for each sysex. If these providers need to communicate, they have to use IPC.
In the appex case, the system instantiates each provider in its own process. If two providers need to communicate, they have to use IPC.
Managing Secrets
An appex runs in a user context and thus can store secrets, like VPN credentials, in the keychain. On macOS this includes both the data protection keychain and the file-based keychain. It can also use a keychain access group to share secrets with its container app. See Sharing access to keychain items among a collection of apps.
Note If you’re not familiar with the different types of keychain available on macOS, see TN3137 On Mac keychain APIs and implementations.
A sysex runs in the global context and thus doesn’t have access to user state. It also doesn’t have access to the data protection keychain. It must use the file-based keychain, and specifically the System keychain. That means there’s no good way to share secrets with the container app.
Instead, do all your keychain operations in the sysex. If the container app needs to work with a secret, have it pass that request to the sysex via IPC. For example, if the user wants to use a digital identity as a VPN credential, have the container app get the PKCS#12 data and password and then pass that to the sysex so that it can import the digital identity into the keychain.
Memory Limits
iOS imposes strict memory limits an NE provider appexen [1]. macOS imposes no memory limits on NE provider appexen or sysexen.
[1] While these limits are not documented officially, you can get a rough handle on the current limits by reading the posts in this thread.
Frameworks
If you want to share code between a Mac app and its embedded appex, use a structure like this:
MyApp.app/
Contents/
MacOS/
MyApp
PlugIns/
MyExtension.appex/
Contents/
MacOS/
MyExtension
…
Frameworks/
MyFramework.framework/
…
There’s one copy of the framework, in the app’s Frameworks directory, and both the app and the appex reference it.
This approach works for an appex because the system always loads the appex from your app’s bundle. It does not work for a sysex. When you activate a sysex, the system copies it to a protected location. If that sysex references a framework in its container app, it will fail to start because that framework isn’t copied along with the sysex.
The solution is to structure your app like this:
MyApp.app/
Contents/
MacOS/
MyApp
Library/
SystemExtensions/
MyExtension.systemextension/
Contents/
MacOS/
MyExtension
Frameworks/
MyFramework.framework/
…
…
That is, have both the app and the sysex load the framework from the sysex’s Frameworks directory. When the system copies the sysex to its protected location, it’ll also copy the framework, allowing the sysex to load it.
To make this work you have to change the default rpath configuration set up by Xcode. Read Dynamic Library Standard Setup for Apps to learn how that works and then tweak things so that:
The framework is embedded in the sysex, not the container app.
The container app has an additional LC_RPATH load command for the sysex’s Frameworks directory (@executable_path/../Library/SystemExtensions/MyExtension.systemextension/Contents/Frameworks).
The sysex’s LC_RPATH load command doesn’t reference the container app’s Frameworks directory (@executable_path/../../../../Frameworks) but instead points to the sysex’s Framweorks directory (@executable_path/../Frameworks).
I am wondering wether iOS allow apps to detect users' proxy.
Topic:
App & System Services
SubTopic:
Networking
Hi, I have a problem about "NSPOSIXErrorDomain Code=65 & iOS18 & Xcode 16".
I used 'CocoaAsyncSocket', '~> 7.6.5'. It works fine on iOS 15.2, But it's worried on iOS 18.3.
Before this, broadcasts can be obtained normally。 I had get socket Multicast Networking.
Please help me .
Topic:
App & System Services
SubTopic:
Networking
I was trying to log the flow description using control filter and data filter. But when I am trying to log the proc ID in control filter, it is always 0, but in data filter, it logs some value. Same goes with the eproc ID. I want to use the flow description data in some other target so I will be sending the data using sockets and I cannot share data from data filter due to its restrictions and control filter isn't providing the proc ID. What should I do?
Hello everyone,
We have a use case where we need to disable the sending and receiving of fragmented packets on the network while using NWConnection.
However, even after setting the disableFragmentation flag to true, the connection still sends fragmented packets.We’ve tried setting the flag as follows, but the packets are still being fragmented:
var connection : NWConnection
var udp_options : NWProtocolUDP.Optionsudp_options = NWProtocolUDP.Options()
var connection_parameters = NWParameters(dtls: nil, udp: udp_options)
let ip_options = connection_parameters.defaultProtocolStack.internetProtocol! as! NWProtocolIP.Options
ip_options.disableFragmentation = true
connection = NWConnection (host: "XX.XX.XX.***", port: NWEndpoint.Port(25000), using: connection_parameters)
The issue we are encountering is that even though we’ve set disableFragmentation to true on the sender, the receiver still receives fragmented UDP packets. This can be observed using Wireshark, where we are sending a 10k byte data from the sender and receiving the fragmented datagram packets on the receiver end while both the devices are on the same WiFi network. Additionally, Wireshark shows that the packet has the "DF" bit set to '0', indicating that fragmentation is allowed.
What is exactly expected from the disableFragmentation flag? Are we misunderstanding how this flag works? Or is there something else we should be doing to ensure that fragmentation is completely disabled?
Looking forward to your insights!
Hi
I just encountered an reachability detection problem by calling SCNetworkReachabilityGetFlags function in iOS 16.
what did I do:
on device iPhone 12, iOS 16.1.1, turn on Airplane Mode, call SCNetworkReachabilityGetFlags, got flags = kSCNetworkReachabilityFlagsTransientConnection | kSCNetworkReachabilityFlagsReachable
on device iPhone 7, iOS 14.5.1, turn on Airplane Mode, call SCNetworkReachabilityGetFlags, got flags = 0
what I expect:
I'm expecting SCNetworkReachabilityGetFlags on my iOS 16.1 device behave same as my iOS 14.5 device, returning flags = 0. It's inappropriate returning kSCNetworkReachabilityFlagsReachable in this case.
Thank you!
Hi!
I am new to Apple app development so please bear with me.
I am trying to design an app that can mimic some of the functionality of iptables routing. The crux of it is I would like to redirect local traffic bound for a specific port to a different port and then redirect any outgoing traffic on that port back to the original port:
outgoing packet bound for IP:1234 -> 127.0.0.1:2345
outgoing packet bound for IP:2345 -> IP:1234
I tried to implement this behavior with a packet tunnel but have not made any substantial progress. Is this the right approach?
Here is my implementation:
private func handleConnection(_ connection: NWConnection) {
connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, context, isComplete, error in
if let data = data, !data.isEmpty {
self?.processData(data, from: connection)
}
if let error = error {
print("Connection error: \(error)")
}
if isComplete {
connection.cancel()
} else {
self?.handleConnection(connection) // Continue to receive data
}
}
connection.start(queue: .main)
}
private func processData(_ data: Data, from connection: NWConnection) {
switch connection.endpoint {
case .hostPort(let host, let port):
let portNumber = port.rawValue
let hostDescription = host.debugDescription
print("Received data from host: \(hostDescription) on port: \(portNumber)")
if portNumber == 1234 {
// Rule 1: Redirect traffic from port 1234 to 127.0.0.1:2345
redirectTraffic(data, to: "127.0.0.1", port: 2345)
print("Redirecting traffic from 1234 to 2345")
} else if portNumber == 2345 {
// Rule 2: Redirect traffic from port 2345 to the original IP address but port 1234
redirectTraffic(data, to: hostDescription, port: 1234)
print("Redirecting traffic from 2345 back to 1234")
}
case .service(name: _, type: _, domain: _, interface: _):
print("Received bonjour service")
case .unix(path: _):
print("Received unix domain path")
case .url(_):
print("Received url")
case .opaque(_):
print("Opaque?")
@unknown default:
fatalError("Unknown endpoint type")
}
}