@cappitolian/network-discovery 0.0.12 → 0.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Package.swift CHANGED
@@ -1,28 +1,28 @@
1
- // swift-tools-version: 5.9
2
- import PackageDescription
3
-
4
- let package = Package(
5
- name: "CappitolianNetworkDiscovery",
6
- platforms: [.iOS(.v15)],
7
- products: [
8
- .library(
9
- name: "CappitolianNetworkDiscovery",
10
- targets: ["NetworkDiscoveryPlugin"])
11
- ],
12
- dependencies: [
13
- .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0")
14
- ],
15
- targets: [
16
- .target(
17
- name: "NetworkDiscoveryPlugin",
18
- dependencies: [
19
- .product(name: "Capacitor", package: "capacitor-swift-pm"),
20
- .product(name: "Cordova", package: "capacitor-swift-pm")
21
- ],
22
- path: "ios/Sources/NetworkDiscoveryPlugin"),
23
- .testTarget(
24
- name: "NetworkDiscoveryPluginTests",
25
- dependencies: ["NetworkDiscoveryPlugin"],
26
- path: "ios/Tests/NetworkDiscoveryPluginTests")
27
- ]
1
+ // swift-tools-version: 5.9
2
+ import PackageDescription
3
+
4
+ let package = Package(
5
+ name: "CappitolianNetworkDiscovery",
6
+ platforms: [.iOS(.v15)],
7
+ products: [
8
+ .library(
9
+ name: "CappitolianNetworkDiscovery",
10
+ targets: ["NetworkDiscoveryPlugin"])
11
+ ],
12
+ dependencies: [
13
+ .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0")
14
+ ],
15
+ targets: [
16
+ .target(
17
+ name: "NetworkDiscoveryPlugin",
18
+ dependencies: [
19
+ .product(name: "Capacitor", package: "capacitor-swift-pm"),
20
+ .product(name: "Cordova", package: "capacitor-swift-pm")
21
+ ],
22
+ path: "ios/Sources/NetworkDiscoveryPlugin"),
23
+ .testTarget(
24
+ name: "NetworkDiscoveryPluginTests",
25
+ dependencies: ["NetworkDiscoveryPlugin"],
26
+ path: "ios/Tests/NetworkDiscoveryPluginTests")
27
+ ]
28
28
  )
package/README.md CHANGED
@@ -1,365 +1,228 @@
1
- # @cappitolian/network-discovery
2
-
3
- A Capacitor plugin for network service discovery using mDNS/Bonjour. Allows automatic server-client connection without manual IP configuration.
4
-
5
- ---
6
-
7
- ## Features
8
-
9
- - **Advertise services** on the local network (server mode)
10
- - **Discover services** automatically (client mode)
11
- - Pass custom data via TXT records (like IP addresses, ports, etc.)
12
- - Real-time service found/lost events
13
- - Works on **iOS** (Bonjour) and **Android** (NSD)
14
- - Tested with **Capacitor 7** and **Ionic 8**
15
-
16
- ---
17
-
18
- ## Installation
19
- ```bash
20
- npm install @cappitolian/network-discovery
21
- npx cap sync
22
- ```
23
-
24
- ---
25
-
26
- ## Usage
27
-
28
- ### Import
29
- ```typescript
30
- import { NetworkDiscovery } from '@cappitolian/network-discovery';
31
- ```
32
-
33
- ### Server Mode - Advertise Your Service
34
- ```typescript
35
- // Start advertising your server
36
- await NetworkDiscovery.startAdvertising({
37
- serviceName: 'MyAppServer',
38
- serviceType: '_http._tcp', // or '_myapp._tcp' for custom service to avoid conflicts with other services
39
- port: 8080,
40
- txtRecord: {
41
- ip: '192.168.1.100', // Your server IP
42
- version: '1.0.0' // Any custom data
43
- }
44
- });
45
-
46
- console.log('Server is now discoverable on the network');
47
-
48
- // Stop advertising when needed
49
- await NetworkDiscovery.stopAdvertising();
50
- ```
51
-
52
- ### Client Mode - Discover Services
53
- ```typescript
54
- // Listen for discovered services
55
- NetworkDiscovery.addListener('serviceFound', (service) => {
56
- console.log('Service discovered:', service);
57
- console.log('Server IP:', service.txtRecord?.ip);
58
- console.log('Server Port:', service.port);
59
- console.log('Server Addresses:', service.addresses);
60
-
61
- // Connect to your server
62
- connectToServer(service.addresses[0], service.port);
63
- });
64
-
65
- // Listen for lost services
66
- NetworkDiscovery.addListener('serviceLost', (service) => {
67
- console.log('Service lost:', service.serviceName);
68
- });
69
-
70
- // Start discovery
71
- await NetworkDiscovery.startDiscovery({
72
- serviceType: '_http._tcp', // Must match the server's serviceType or '_myapp._tcp' for custom service to avoid conflicts with other services
73
- domain: 'local.' // Optional, defaults to 'local.'
74
- });
75
-
76
- // Stop discovery when needed
77
- await NetworkDiscovery.stopDiscovery();
78
-
79
- // Clean up listeners
80
- await NetworkDiscovery.removeAllListeners();
81
- ```
82
-
83
- ### Complete Example - Auto-Connect Flow
84
-
85
- **Server Side:**
86
- ```typescript
87
- import { NetworkDiscovery } from '@cappitolian/network-discovery';
88
- import { Network } from '@capacitor/network';
89
-
90
- async startServer() {
91
- // Get device IP
92
- const ip = await this.getLocalIP();
93
-
94
- // Advertise server
95
- await NetworkDiscovery.startAdvertising({
96
- serviceName: 'MyAppServer',
97
- serviceType: '_http._tcp', // Must match the server's serviceType or '_myapp._tcp' for custom service to avoid conflicts with other services
98
- port: 8080,
99
- txtRecord: {
100
- ip: ip,
101
- serverName: 'Production Server'
102
- }
103
- });
104
-
105
- console.log('Server advertising on network');
106
- }
107
-
108
- async getLocalIP(): Promise<string> {
109
- const status = await Network.getStatus();
110
- // Your IP extraction logic here
111
- return '192.168.1.100';
112
- }
113
- ```
114
-
115
- **Client Side:**
116
- ```typescript
117
- import { NetworkDiscovery } from '@cappitolian/network-discovery';
118
-
119
- async findAndConnectToServer() {
120
- return new Promise((resolve, reject) => {
121
-
122
- // Listen for server
123
- NetworkDiscovery.addListener('serviceFound', async (service) => {
124
- if (service.serviceName === 'MyAppServer') {
125
- console.log('Server found!');
126
-
127
- const serverIP = service.txtRecord?.ip || service.addresses[0];
128
- const serverPort = service.port;
129
-
130
- // Stop discovery
131
- await NetworkDiscovery.stopDiscovery();
132
- await NetworkDiscovery.removeAllListeners();
133
-
134
- // Connect to server
135
- resolve({ ip: serverIP, port: serverPort });
136
- }
137
- });
138
-
139
- // Start discovery
140
- NetworkDiscovery.startDiscovery({
141
- serviceType: '_http._tcp' // Must match the server's serviceType or '_myapp._tcp' for custom service to avoid conflicts with other services
142
- });
143
-
144
- // Timeout after 10 seconds
145
- setTimeout(() => {
146
- reject(new Error('Server not found'));
147
- }, 10000);
148
- });
149
- }
150
-
151
- // Usage
152
- async onLoginClick() {
153
- try {
154
- const server = await this.findAndConnectToServer();
155
- console.log(`Connecting to ${server.ip}:${server.port}`);
156
- // Your connection logic here
157
- } catch (error) {
158
- console.error('Could not find server:', error);
159
- }
160
- }
161
- ```
162
-
163
- ---
164
-
165
- ## API Reference
166
-
167
- ### Methods
168
-
169
- #### `startAdvertising(options: AdvertisingOptions)`
170
-
171
- Publishes a service on the local network.
172
-
173
- **Parameters:**
174
- - `serviceName` (string): Name of your service (e.g., "MyAppServer")
175
- - `serviceType` (string): Service type (e.g., "_http._tcp", "_myapp._tcp")
176
- - `port` (number): Port number your server is listening on
177
- - `txtRecord` (object, optional): Key-value pairs to broadcast (e.g., IP, version)
178
-
179
- **Returns:** `Promise<{ success: boolean }>`
180
-
181
- ---
182
-
183
- #### `stopAdvertising()`
184
-
185
- Stops advertising the service.
186
-
187
- **Returns:** `Promise<{ success: boolean }>`
188
-
189
- ---
190
-
191
- #### `startDiscovery(options: DiscoveryOptions)`
192
-
193
- Starts searching for services on the local network.
194
-
195
- **Parameters:**
196
- - `serviceType` (string): Type of service to search for (must match server's type)
197
- - `domain` (string, optional): Domain to search in (default: "local.")
198
-
199
- **Returns:** `Promise<void>`
200
-
201
- ---
202
-
203
- #### `stopDiscovery()`
204
-
205
- Stops the service discovery.
206
-
207
- **Returns:** `Promise<{ success: boolean }>`
208
-
209
- ---
210
-
211
- ### Events
212
-
213
- #### `serviceFound`
214
-
215
- Fired when a service is discovered.
216
-
217
- **Payload:**
218
- ```typescript
219
- {
220
- serviceName: string;
221
- serviceType: string;
222
- domain: string;
223
- hostName: string;
224
- port: number;
225
- addresses: string[]; // Array of IP addresses
226
- txtRecord?: { // Custom data from server
227
- [key: string]: string;
228
- };
229
- }
230
- ```
231
-
232
- ---
233
-
234
- #### `serviceLost`
235
-
236
- Fired when a previously discovered service is no longer available.
237
-
238
- **Payload:**
239
- ```typescript
240
- {
241
- serviceName: string;
242
- serviceType: string;
243
- }
244
- ```
245
-
246
- ---
247
-
248
- ## Service Type Format
249
-
250
- Service types must follow the format: `_name._protocol`
251
-
252
- **Common examples:**
253
- - `_http._tcp` - HTTP service
254
- - `_https._tcp` - HTTPS service
255
- - `_myapp._tcp` - Custom app service
256
- - `_ssh._tcp` - SSH service
257
-
258
- **Recommended for apps:** Use a custom service type like `_myapp._tcp` to avoid conflicts with other services.
259
-
260
- ---
261
-
262
- ## Permissions
263
-
264
- ### Android
265
-
266
- Add to `AndroidManifest.xml`:
267
- ```xml
268
- <uses-permission android:name="android.permission.INTERNET" />
269
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
270
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
271
- <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
272
- ```
273
-
274
- ### iOS
275
-
276
- No additional permissions required. Bonjour is enabled by default.
277
-
278
- Optionally, add to `Info.plist` to declare your service:
279
- ```xml
280
- <key>NSBonjourServices</key>
281
- <array>
282
- <string>_myapp._tcp</string>
283
- </array>
284
- ```
285
-
286
- ---
287
-
288
- ## Platforms
289
-
290
- - **iOS** (Bonjour/NetService)
291
- - **Android** (Network Service Discovery)
292
- - **Web** (Not implemented - throws unimplemented error)
293
-
294
- ---
295
-
296
- ## Requirements
297
-
298
- - [Capacitor 7+](https://capacitorjs.com/)
299
- - [Ionic 8+](https://ionicframework.com/) (optional, but tested)
300
- - iOS 12.0+
301
- - Android API 16+ (Android 4.1+)
302
-
303
- ---
304
-
305
- ## Troubleshooting
306
-
307
- ### Services not being discovered
308
-
309
- 1. **Check both devices are on the same WiFi network**
310
- 2. **Verify service types match** exactly between server and client
311
- 3. **Check firewall settings** - some networks block mDNS
312
- 4. **Android:** Ensure multicast is enabled on your network
313
- 5. **iOS:** Make sure device is not in Low Power Mode
314
-
315
- ### Server not advertising
316
-
317
- 1. **Verify port is not in use** by another service
318
- 2. **Check network permissions** are granted
319
- 3. **Restart the app** after installing the plugin
320
-
321
- ### General debugging
322
-
323
- Enable verbose logging:
324
- ```typescript
325
- // Check plugin is loaded
326
- console.log('Plugin available:', NetworkDiscovery);
327
-
328
- // Log all events
329
- NetworkDiscovery.addListener('serviceFound', (s) => console.log('Found:', s));
330
- NetworkDiscovery.addListener('serviceLost', (s) => console.log('Lost:', s));
331
- ```
332
-
333
- ---
334
-
335
- ## Use Cases
336
-
337
- - **Auto-connect apps** - Client automatically finds and connects to server
338
- - **Local multiplayer games** - Discover game hosts on LAN
339
- - **IoT device discovery** - Find smart devices without configuration
340
- - **File sharing apps** - Discover peers for file transfer
341
- - **Remote control apps** - Find controllable devices automatically
342
-
343
- ---
344
-
345
- ## License
346
-
347
- MIT
348
-
349
- ---
350
-
351
- ## Support
352
-
353
- If you encounter any issues or have feature requests, please open an issue on the [GitHub repository](https://github.com/alessandrycruz1987/network-discovery).
354
-
355
- ---
356
-
357
- ## Contributing
358
-
359
- Contributions are welcome! Please feel free to submit a Pull Request.
360
-
361
- ---
362
-
363
- ## Credits
364
-
365
- Created for use with Capacitor 7 and Ionic 8 applications requiring automatic network service discovery.
1
+ # @cappitolian/network-discovery
2
+
3
+ A Capacitor plugin for network service discovery using mDNS/Bonjour. Allows automatic server-client connection without manual IP configuration.
4
+
5
+ ---
6
+
7
+ ## Features
8
+
9
+ - **Publish services** on the local network (server mode)
10
+ - **Discover services** automatically (client mode)
11
+ - Pass custom metadata via TXT records (like HTTP port, version, etc.)
12
+ - Anti-ghosting IP resolution logic
13
+ - Works on **iOS** (Bonjour/NWListener) and **Android** (NSD)
14
+ - Cross-platform compatible: iOS Android in both directions
15
+ - Tested with **Capacitor 7** and **Ionic 8**
16
+
17
+ ---
18
+
19
+ ## Installation
20
+ ```bash
21
+ npm install @cappitolian/network-discovery
22
+ npx cap sync
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Usage
28
+
29
+ ### Import
30
+ ```typescript
31
+ import { NetworkDiscovery } from '@cappitolian/network-discovery';
32
+ ```
33
+
34
+ ### Server Mode - Publish Your Service
35
+ ```typescript
36
+ // Start publishing your server
37
+ await NetworkDiscovery.startServer({
38
+ serviceName: 'SSSPOSServer',
39
+ serviceType: '_ssspos._tcp',
40
+ port: 8081, // Discovery service port
41
+ ip: '192.168.1.100', // Your server IP
42
+ metadata: {
43
+ httpPort: '8080', // Your actual HTTP server port
44
+ version: '1.0.0', // Any custom data
45
+ deviceName: 'Main Server'
46
+ }
47
+ });
48
+
49
+ console.log('Server is now discoverable on the network');
50
+
51
+ // Stop publishing when needed
52
+ await NetworkDiscovery.stopServer();
53
+ ```
54
+
55
+ ### Client Mode - Discover Services
56
+ ```typescript
57
+ // Find a server on the network
58
+ const result = await NetworkDiscovery.findServer({
59
+ serviceName: 'SSSPOSServer',
60
+ serviceType: '_ssspos._tcp',
61
+ timeout: 15000 // Optional, defaults to 10000ms
62
+ });
63
+
64
+ if (result) {
65
+ console.log('Server found!');
66
+ console.log('IP:', result.ip);
67
+ console.log('Discovery Port:', result.port);
68
+ console.log('HTTP Port:', result.metadata.httpPort);
69
+ console.log('Version:', result.metadata.version);
70
+
71
+ // Connect to your HTTP server
72
+ const httpUrl = `http://${result.ip}:${result.metadata.httpPort}`;
73
+ // Make your API calls here
74
+ } else {
75
+ console.log('Server not found within timeout');
76
+ }
77
+ ```
78
+
79
+ ---
80
+
81
+ ## API Reference
82
+
83
+ ### Methods
84
+
85
+ #### `startServer(options: StartServerOptions)`
86
+
87
+ Publishes a service on the local network.
88
+
89
+ **Parameters:**
90
+ ```typescript
91
+ {
92
+ serviceName: string; // Name of your service
93
+ serviceType: string; // Service type (e.g., "_ssspos._tcp")
94
+ port: number; // Discovery service port
95
+ ip: string; // Your server IP address
96
+ metadata?: { // Optional custom key-value pairs
97
+ [key: string]: string;
98
+ };
99
+ }
100
+ ```
101
+
102
+ #### `stopServer()`
103
+
104
+ Stops publishing the service.
105
+
106
+ #### `findServer(options: FindServerOptions)`
107
+
108
+ Searches for a service on the local network.
109
+
110
+ **Parameters:**
111
+ ```typescript
112
+ {
113
+ serviceName: string;
114
+ serviceType: string;
115
+ timeout?: number; // Default: 10000ms
116
+ }
117
+ ```
118
+
119
+ **Returns:**
120
+ ```typescript
121
+ {
122
+ ip: string;
123
+ port: number;
124
+ metadata: { [key: string]: string };
125
+ }
126
+ ```
127
+
128
+ ---
129
+
130
+ ## Architecture Best Practices
131
+
132
+ ### Separate Ports Pattern
133
+ ```
134
+ Port 8080 HTTP Server (GET, POST, API endpoints)
135
+ Port 8081 Network Discovery (mDNS/Bonjour)
136
+ ```
137
+
138
+ **Why:**
139
+ 1. Avoids port binding conflicts
140
+ 2. Clear separation of concerns
141
+ 3. Easier debugging
142
+ 4. HTTP server can restart without affecting discovery
143
+
144
+ ---
145
+
146
+ ## Permissions
147
+
148
+ ### Android
149
+ ```xml
150
+ <uses-permission android:name="android.permission.INTERNET" />
151
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
152
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
153
+ <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
154
+ ```
155
+
156
+ ### iOS
157
+ ```xml
158
+ <key>NSLocalNetworkUsageDescription</key>
159
+ <string>This app needs access to the local network to discover and connect to other devices.</string>
160
+
161
+ <key>NSBonjourServices</key>
162
+ <array>
163
+ <string>_ssspos._tcp</string>
164
+ </array>
165
+ ```
166
+
167
+ ---
168
+
169
+ ## Cross-Platform Compatibility
170
+
171
+ | Server Client | Status |
172
+ |----------------|--------|
173
+ | Android → Android | ✅ Working |
174
+ | Android iOS | Working |
175
+ | iOS Android | Working |
176
+ | iOS iOS | Working |
177
+
178
+ ---
179
+
180
+ ## Troubleshooting
181
+
182
+ ### Services not being discovered
183
+
184
+ 1. Check both devices are on same WiFi network
185
+ 2. Verify service types match exactly
186
+ 3. Check firewall/router settings (some block mDNS)
187
+ 4. Android: Ensure multicast is enabled
188
+ 5. iOS: Device not in Low Power Mode
189
+
190
+ ### iOS Server not visible to Android
191
+
192
+ **Fixed in v1.0.0+**
193
+
194
+ If still experiencing issues:
195
+ 1. Update to latest version
196
+ 2. Use separate ports (8080 for HTTP, 8081 for discovery)
197
+ 3. Check logs for "iOS Servidor LISTO" (iOS) and "NSD_DEBUG" (Android)
198
+
199
+ ### Debugging
200
+
201
+ **Android:**
202
+ ```bash
203
+ adb logcat | grep NSD_DEBUG
204
+ ```
205
+
206
+ **iOS:**
207
+ Look for logs with `NSD_LOG:` in Xcode Console
208
+
209
+ ---
210
+
211
+ ## Changelog
212
+
213
+ ### v1.0.0 (Current)
214
+ - ✅ Fixed iOS server → Android client discovery
215
+ - Added anti-ghosting IP resolution
216
+ - ✅ Improved cross-platform compatibility
217
+ - ✅ Enhanced logging for debugging
218
+ - ✅ Support for separate discovery/HTTP ports
219
+
220
+ ---
221
+
222
+ ## License
223
+
224
+ MIT
225
+
226
+ ## Credits
227
+
228
+ Developed by Alessandry Cruz for Cappitolian projects.