@@ -133,50 +133,55 @@ export function pluginDev(
133
133
}
134
134
}
135
135
136
- export async function findIp ( family : 'v4' | 'v6' ) : Promise < string > {
136
+ export async function findIp (
137
+ family : 'v4' | 'v6' ,
138
+ isInternal = false ,
139
+ ) : Promise < string > {
137
140
const [
138
- { default : defaultGateway } ,
139
141
{ default : ipaddr } ,
140
142
os ,
141
143
] = await Promise . all ( [
142
- import ( 'default-gateway' ) ,
143
-
144
144
import ( 'ipaddr.js' ) ,
145
145
import ( 'node:os' ) ,
146
146
] )
147
- const gateway = await ( async ( ) => {
148
- if ( family === 'v4' ) {
149
- const { gateway } = await defaultGateway . gateway4async ( )
150
- return gateway
151
- } else {
152
- const { gateway } = await defaultGateway . gateway6async ( )
153
- return gateway
154
- }
155
- } ) ( )
156
- const gatewayIp = ipaddr . parse ( gateway )
157
-
158
- // Look for the matching interface in all local interfaces.
159
- for ( const addresses of Object . values ( os . networkInterfaces ( ) ) ) {
160
- if ( ! addresses ) {
161
- continue
162
- }
163
-
164
- for ( const { cidr, internal } of addresses ) {
165
- if ( ! cidr || internal ) {
166
- continue
147
+
148
+ let host : string | undefined
149
+
150
+ Object . values ( os . networkInterfaces ( ) )
151
+ . flatMap ( ( networks ) => networks ?? [ ] )
152
+ . filter ( ( network ) => {
153
+ if ( ! network || ! network . address ) {
154
+ return false
167
155
}
168
156
169
- const net = ipaddr . parseCIDR ( cidr )
157
+ if ( network . family !== `IP${ family } ` ) {
158
+ return false
159
+ }
170
160
171
- if (
172
- net [ 0 ]
173
- && net [ 0 ] . kind ( ) === gatewayIp . kind ( )
174
- && gatewayIp . match ( net )
175
- ) {
176
- return net [ 0 ] . toString ( )
161
+ if ( network . internal !== isInternal ) {
162
+ return false
177
163
}
178
- }
164
+
165
+ if ( family === 'v6' ) {
166
+ const range = ipaddr . parse ( network . address ) . range ( )
167
+
168
+ if ( range !== 'ipv4Mapped' && range !== 'uniqueLocal' ) {
169
+ return false
170
+ }
171
+ }
172
+
173
+ return network . address
174
+ } )
175
+ . forEach ( ( network ) => {
176
+ host = network . address
177
+ if ( host . includes ( ':' ) ) {
178
+ host = `[${ host } ]`
179
+ }
180
+ } )
181
+
182
+ if ( ! host ) {
183
+ throw new Error ( `No valid IP found` )
179
184
}
180
185
181
- throw new Error ( `No valid IP found for the default gateway ${ gateway } ` )
186
+ return host
182
187
}
0 commit comments