I need to create a function in Google sheet to get my external (public) IP address
I tried use function =IMPORTXML("https://api.myip.com","//body")
, but this method shows diffrint IP address not my external IP address
I need to create a function in Google sheet to get my external (public) IP address
I tried use function =IMPORTXML("https://api.myip.com","//body")
, but this method shows diffrint IP address not my external IP address
the reason the IP is different is because you are getting the IP of Google Sheets location not your IP
The following solution makes use of a custom menu in the Spreadsheets -
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('My Menu')
.addItem('Get IP', 'getIP')
.addToUi();
}
function getIP() {
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().appendRow([JSON.parse(UrlFetchApp.fetch('https://api6.ipify.org?format=json')).ip]);
}
You're free to modify the script to place said IP anywhere in the sheet, as required.
Also, I'm making use of the IPv6 address, as opposed to IPv4 but should you want to switch it to IPv4, replace the URL from the code to https://api.ipify.org?format=json
- you may find this resource here.
I've asked out & around and this cannot (in any way) be achieved via a custom formulae, as such formulas run within a wrapper of sorts (that do not interact with any client-side elements). Hope this helps.
Adding a way to insert external IP using custom menu to the specific cell (current cell, to be precise) -
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('My Menu')
.addItem('Get IP', 'getIP')
.addToUi();
}
function getIP() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var currentCell = sheet.getCurrentCell();
var ip = JSON.parse(UrlFetchApp.fetch('https://api6.ipify.org?format=json')).ip;
currentCell.setValue(ip)
}
By using this method, the IP would be added to the cell that has been selected.
You may wonder why current cell was chosen instead of active cell - well, the answer to that is because the document prefers us to do so :) I bet it would work even if we were to use active cell (haven't tested that though but I don't see a reason why it wouldn't)
It's not possible to use a Google Sheets custom function or Google Apps Script server side address to get you external IP because the related code is executed on the server side and Google Apps Script services doesn't include methods to get that but you could use client-side code to the get the external IP address. Additional, if it is required to send the IP address to an spreadsheet, the you could use do that by using google.script.run
or the Google Sheets API.
NOTE: The closest Google Apps Script classes are Class Session and Class User.
Related
References