2015年4月8日 星期三

[Corona SDK] How to get local IP and Public Internet IP?

If we access the Internet through some AP, we should get a local IP provided by the AP.
To get the local IP, we can use the method shown below:
local getIP = function()
    local s = socket.connect("www.google.com", 80)--need to have internet connection
    local ip, _ = s:getsockname()
    print( "myIP:", ip)
    text1 = display.newText( "Local IP:"..ip, display.contentCenterX, 40, native.systemFontBold, 24 )
    text1:setFillColor( 1,1,0 )
    return ip
end

getIP()
The method mentioned above need to performed with Internet connection available.
It just connects to some open website, such as "www.google.com" in our example.
You can connect to other website if you want.

For local IP, we may want to get such information without the Internet connection.
To achieve this, we can use the following way:
local getIP = function()
    local s = socket.udp()  --creates a UDP object
    s:setpeername( "1.1.1.1", 80 )--No need to have internet connection
    local ip, _ = s:getsockname()
    print( "myIP:", ip)
    text1 = display.newText( "Local IP:"..ip, display.contentCenterX, 0, native.systemFontBold, 24 )
    text1:setFillColor( 1,1,0 )
    return ip
end

getIP()
We establish a UDP connection and then we can get our own local IP.
The target "1.1.1.1" can be any IP.
It doesn't matter since we don't really transfer any data.

What if we want to get the public Internet IP of our device?
We can get it through some website which can provide such information.
function findPublicIPAddress()
    
    local getipScriptURL = "http://myip.dnsomatic.com/"
    local DeviceIP
    
    function ipListener(event)
        if not event.isError and event.response ~= "" then
            DeviceIP = event.response 
            print("Public DeviceIP:"..DeviceIP)
            text1 = display.newText( "Public IP:"..DeviceIP, display.contentCenterX, 80, native.systemFontBold, 24 )
            text1:setFillColor( 0,1,1 )
        end
    end
    
    network.request(getipScriptURL,"GET",ipListener) 
    
end
 
findPublicIPAddress()
Of course, we should have Internet connection for running above example.

沒有留言:

張貼留言