@@ -58,6 +58,28 @@ function matchName(actualFamily: string | number, expectedFamily: string | numbe
5858 return actualFamily === expectedFamily ;
5959}
6060
61+ function findAddressFromInterface ( items : os . NetworkInterfaceInfo [ ] , expectedFamily : string | number ,
62+ ignoreLoAddress = false ) {
63+ let firstMatchItem ;
64+ for ( const item of items ) {
65+ if ( matchName ( item . family , expectedFamily ) ) {
66+ if ( ignoreLoAddress && item . address . startsWith ( '127.' ) ) {
67+ continue ;
68+ }
69+ if ( expectedFamily === 'IPv6' ) {
70+ // find the scopeid = 0 item
71+ if ( item . scopeid === 0 ) return item ;
72+ if ( ! firstMatchItem ) {
73+ firstMatchItem = item ;
74+ }
75+ } else {
76+ return item ;
77+ }
78+ }
79+ }
80+ return firstMatchItem ;
81+ }
82+
6183export function getInterfaceAddress ( family ?: string , name ?: string ) {
6284 const interfaces = os . networkInterfaces ( ) ;
6385 const noName = ! name ;
@@ -68,10 +90,9 @@ export function getInterfaceAddress(family?: string, name?: string) {
6890 const interfaceName = name + ( i >= 0 ? i : '' ) ; // support 'lo' and 'lo0'
6991 const items = interfaces [ interfaceName ] ;
7092 if ( items ) {
71- for ( const item of items ) {
72- if ( matchName ( item . family , family ) ) {
73- return item ;
74- }
93+ const item = findAddressFromInterface ( items , family ) ;
94+ if ( item ) {
95+ return item ;
7596 }
7697 }
7798 }
@@ -82,11 +103,10 @@ export function getInterfaceAddress(family?: string, name?: string) {
82103 for ( const k in interfaces ) {
83104 const items = interfaces [ k ] ;
84105 if ( items ) {
85- for ( const item of items ) {
86- // all 127 addresses are local and should be ignored
87- if ( matchName ( item . family , family ) && ! item . address . startsWith ( '127.' ) ) {
88- return item ;
89- }
106+ // all 127 addresses are local and should be ignored
107+ const item = findAddressFromInterface ( items , family , true ) ;
108+ if ( item ) {
109+ return item ;
90110 }
91111 }
92112 }
0 commit comments