JSFiddle - React, Tailwind, and code Playground

by juberti

HTML

<button onclick="start()">
Start
</button>

JavaScript

async function discover(ip) {
  const pc1 = new RTCPeerConnection();
  const pc2 = new RTCPeerConnection();

  let done = false;
  pc2.onicecandidate = e => {
    if (!e.candidate || done) return;
    done = true;  
    const parts = e.candidate.candidate.split(' ');
    if (parts[4].indexOf('.local') === -1) {
      console.log('has gum permission, repeat without', JSON.stringify(parts[4]))
    } else {
      parts[4] = ip;
      pc1.addIceCandidate({sdpMid: e.candidate.sdpMid, sdpMLineIndex: e.candidate.sdpMLineIndex, candidate: parts.join(' ')})
    }
  };
  pc1.createDataChannel("foo");
  pc2.ondatachannel = async () => {
    console.log('this connection worked', ip);
    window.alert(ip);
  }
  const offer = await pc1.createOffer();
  await pc2.setRemoteDescription(offer);
  await pc1.setLocalDescription(offer);
  const answer = await pc2.createAnswer();
  await pc1.setRemoteDescription(answer);
  await pc2.setLocalDescription(answer);
}

function start() {
  for (let i = 1; i < 256; ++i) {
    for (let j = 1; j < 256; ++j) {
      const ip = '192.168.' + i + '.' + j;
      if (j == 1) {
        console.log('Probing ' + ip);
      }
      discover(ip);
    }
  }
}