Created
December 11, 2019 15:01
-
-
Save M4rkux/e8b3d0f3241ada0f9b93da40c6901e8e to your computer and use it in GitHub Desktop.
Get IP address with TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getIpAddress() { | |
return new Promise((resolve, reject) => { | |
var rtc = new RTCPeerConnection(); | |
rtc.createDataChannel(''); | |
rtc.onicecandidate = function (evt) { | |
if (evt.candidate) grepSDP("a="+evt.candidate.candidate); | |
}; | |
rtc.createOffer().then(function (offerDesc) { | |
grepSDP(offerDesc.sdp); | |
rtc.setLocalDescription(offerDesc); | |
}, | |
function (e) { | |
reject(e); | |
}); | |
function grepSDP(sdp) { | |
const line = sdp.split('\r\n').find((line) => line.includes("a=candidate")); | |
if (line) { | |
var parts = line.split(' '), | |
addr = parts[4], | |
type = parts[7]; | |
if (type === 'host') { | |
const strAddr: string = addr.split('.').join('_'); | |
resolve(strAddr); | |
} | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment