getIP.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. export function getUserIP(onNewIP) { // onNewIp - your listener function for new IPs
  2. // compatibility for firefox and chrome
  3. var MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection
  4. var pc = new MyPeerConnection({
  5. iceServers: []
  6. })
  7. var noop = function() { }
  8. var localIPs = {}
  9. var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g
  10. function iterateIP(ip) {
  11. if (!localIPs[ip]) onNewIP(ip)
  12. localIPs[ip] = true
  13. }
  14. // create a bogus data channel
  15. pc.createDataChannel('')
  16. // create offer and set local description
  17. try {
  18. pc.createOffer(function(sdp) {
  19. sdp.sdp.split('\n').forEach(function(line) {
  20. if (line.indexOf('candidate') < 0) return
  21. line.match(ipRegex).forEach(iterateIP)
  22. })
  23. pc.setLocalDescription(sdp, noop, noop)
  24. }, function(sdp) {
  25. console.log('fail')
  26. })
  27. } catch (err) {
  28. console.log(err)
  29. }
  30. // listen for candidate events
  31. pc.onicecandidate = function(ice) {
  32. if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return
  33. ice.candidate.candidate.match(ipRegex).forEach(iterateIP)
  34. }
  35. }