cocos2d-lua 如何获取客户端ip地址和归属地

看这个问题呢,首先看一下这个链接:

"http://pv.sohu.com/cityjson?ie=utf-8"

这个呢是通过http请求ip

我们在lua中就可以利用这个获取ip地址和归属地

function getInternetIP()
    HttpUtils:requestHttp(GameConfig:getIPUrl(), function(result, response) getIPCallback(result, response) end)
end

function getIPCallback(result, response)
    if result == false then
    else
        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
        
    end
end

requestHttp 的方法也贴一下吧:

function HttpUtils:requestHttp(url, callback, responseType, data)
    luaPrint(url)
    callback = callback or nil;

    if responseType == nil then
        responseType = "GET";
    end

    local xhr = cc.XMLHttpRequest:new()
    xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
    xhr:open(responseType, url)
    local function onReadyStateChanged()
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
            -- luaPrint("xhr.response ------------  "..xhr.response)

            if callback then
                callback(true, xhr.response);
            end
        else
            luaPrint("xhr.readyState is:", xhr.readyState, "xhr.status is:         ",xhr.status)
            if callback then
                callback(false, xhr.response);
            end
        end

        xhr:unregisterScriptHandler()
    end
    xhr:registerScriptHandler(onReadyStateChanged)

    if data ~= nil and data ~= "" then
        xhr:send(data);
    else
        xhr:send()
    end
end

好了,代码都贴出来了,接下我们试一下:

好了,获取ip成功,这个归属地有的时候能获取到杭州市有的时候只能获取到浙江省,这个就不管了。

Guess you like

Origin blog.csdn.net/pyf_914406232/article/details/103234413