cocos-lua 獲取IP 歸屬地

奶娃小嘴發表於2021-01-04
--獲取ip
function Tools:getIp( )
	local xhr = cc.XMLHttpRequest:new()
    xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
    xhr:open("GET", "http://pv.sohu.com/cityjson?ie=utf-8")
    local function onReadyStateChanged()
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
        	local response= xhr.response
            local startPos = string.find(response,"{")
        	local endPos = string.find(response,"}")
        	local jsonStr = string.sub(response,startPos,endPos)
        	local tb = json.decode(jsonStr)
        	--獲取的ip地址
        	local ip = tb.cip
        	--獲取歸屬地
        	local cname = tb.cname
        	self:log("ip ".. ip .. " 歸屬地 " .. cname)
        	return ip
        else
            return "0.0.0.0"
        end
        xhr:unregisterScriptHandler()
    end
    xhr:registerScriptHandler(onReadyStateChanged)
    xhr:send()
end

 

相關文章