11import sys from 'syscall-napi'
2- import ipaddr from 'ipaddr.js'
2+ import ip from 'ipaddr.js'
33import { Socket } from 'node:net'
44import dns from 'node:dns/promises'
55import { strict as assert } from 'node:assert'
@@ -39,9 +39,10 @@ async function enableFreebind(fd) {
3939
4040// todo: createDgram
4141export async function createSocket ( host , port , localAddress , connectOptions ) {
42- const addrFamily = ipaddr . parse ( host ) . kind ( )
43- if ( connectOptions . strict !== false )
44- assert ( addrFamily == ipaddr . parse ( localAddress ) . kind ( ) )
42+ const addrFamily = ip . parse ( host ) . kind ( )
43+ if ( connectOptions . strict !== false ) {
44+ assert ( addrFamily == ip . parse ( localAddress ) . kind ( ) )
45+ }
4546
4647 const fd = await initSocket ( addrFamily , 'tcp' ) ;
4748 await enableFreebind ( fd ) ;
@@ -71,17 +72,28 @@ async function lookup(hostname, family) {
7172 return host ;
7273}
7374
74- // `bits` defines how many bits to fill from the MSB to the LSB
75- // needs to be <= length of the prefix
76- export async function createRandomSocket ( hostname , port , localCIDR , options ) {
77- const { bits, strict, ...connectOptions } = options ;
78- const { addr, kind } = generateRandomIP ( localCIDR , bits ) ;
75+ export async function createSocketFromHostname ( hostname , port , sourceIP , options ) {
76+ const { strict, ...connectOptions } = options ;
77+
78+ const kind = ip . parse ( sourceIP ) . kind ( ) ;
7979 const family = ( { 'ipv4' : 4 , 'ipv6' : 6 } ) [ kind ] ;
8080
8181 const host = await lookup ( hostname , family ) ;
8282 const familyMatching = family === host . family ;
83- if ( ! familyMatching && strict !== false )
84- throw 'family mismatch for addr ' + host . address
83+ if ( ! familyMatching && strict !== false ) {
84+ throw 'family mismatch for addr ' + host . address ;
85+ }
8586
86- return await createSocket ( host . address , port , addr , { ...connectOptions , strict, familyMatching } )
87+ return createSocket (
88+ host . address , port , sourceIP ,
89+ { ...connectOptions , strict, familyMatching }
90+ ) ;
91+ }
92+
93+ // `bits` defines how many bits to fill from the MSB to the LSB
94+ // needs to be <= length of the prefix
95+ export function createRandomSocket ( hostname , port , localCIDR , options ) {
96+ const { bits, ...rest } = options ;
97+ const addr = generateRandomIP ( localCIDR , bits ) ;
98+ return createSocketFromHostname ( hostname , port , addr , rest ) ;
8799}
0 commit comments