const dgram = require('dgram')
function broadcastFix(){
	//广播，设置非同网段控制卡的新ip
	getPreFix().forEach(function(item){
		// alert(JSON.stringify(item))
		try{
			var message = getFixMessage2(item)
      // alert(message)
			var socket = dgram.createSocket('udp4')
			socket.on('listening', () => {
			  var address = socket.address();
			  alert(`socket listening ${address.address}:${address.port}`);
			});
			
			socket.bind(null, item.address, function () {
				socket.setBroadcast(true);
				socket.send(message, 0, message.length, 31296, '255.255.255.255', (err,size) => {
					socket.close();
					alert('OK')
				});	
			});
		}catch(e){
			console.log(e)
    }
	})
}
function getPreFix(){
	var result = []
	var os = require('os')
	var its = os.networkInterfaces()
	for(var i in its){
		var arr = its[i]
		for(var j in arr){
			var info = arr[j]
			if(info && info.family.toLowerCase() =='ipv4' && info.address != '127.0.0.1'){
				var ip = info.address.split('.')
				var mask = info.netmask.split('.')
				var network = []
				for(var i=0;i<4; i++){
					network[i]= ip[i] & mask[i]
				}
				var broadAddress = []
				for(var i=0; i<4; i++){
					broadAddress[i] = network[i] | (255-mask[i])
				}
				//newData
				network[3]++
				var gateway = network.join('.')
				broadAddress[3]--
				if(broadAddress[3] == ip[3])
					broadAddress[3]--
				var newIp = broadAddress.join('.')
				result.push({
					address:info.address,
					newIp:newIp,
					mask:info.netmask,
					gateway:gateway,
					dns:gateway
				})
			}
		}
	}
	return result
}




function getFixMessage(item){
	var buf = new Buffer(109)
	buf.writeInt8(0x7e, 0)
	buf.writeInt8(0x7e, 1)
	buf.writeInt8(0x7e, 2)
	buf.writeInt8(0x43, 3)
	buf.writeInt32LE(80, 24)
	buf.write(item.newIp, 28, 'ascii')
	buf.write(item.mask, 48, 'ascii')
	buf.write(item.gateway, 68, 'ascii')
	buf.write(item.dns, 88, 'ascii')
	//计算校验
	var checkByte = 0
	var lastIndex = 108
	for (var i = 3; i < lastIndex; i++) {
		checkByte += buf.readInt8(i)
	}
	buf.writeUint8(0xff^(0xff & checkByte), lastIndex)
	return buf
}

function getFixMessage2(item){
	var dv = new DataView(new ArrayBuffer(3+1+20+4+80+1))
	dv.setInt8(0, 0x7e)
	dv.setInt8(1, 0x7e)
	dv.setInt8(2, 0x7e)
	dv.setInt8(3, 0x43)
	dv.setInt32(24, 80, true) //正文长度  byteOffset, value [, littleEndian]
	for(var i=0; i< item.newIp.length; i++){
		dv.setInt8(28+i, item.newIp.charCodeAt(i))
	}
	for(var i=0; i< item.mask.length; i++){
		dv.setInt8(48+i, item.mask.charCodeAt(i))
	}
	for(var i=0; i< item.gateway.length; i++){
		dv.setInt8(68+i, item.gateway.charCodeAt(i))
	}
	for(var i=0; i< item.dns.length; i++){
		dv.setInt8(88+i, item.dns.charCodeAt(i))
	}	
	//计算校验
	var checkByte = 0
	var lastIndex = dv.byteLength - 1

	for (var i = 3; i < lastIndex; i++) {
		checkByte += dv.getInt8(i)
	}
	dv.setInt8(lastIndex, ~(checkByte & 0xff))
	return Buffer.from(dv.buffer)
}

exports. broadcastFix=broadcastFix