AP會給你的裝置一個local IP,
要取得這個IP,可利用下面方式:
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()
上面的方式需要在有連網的情形下執行,
它是連到某個開放網站,例如"www.google.com",
當然,你也可以連到其它網站,
因為是取得local IP,有時會希望在沒有連上網路時也能取得這樣的資訊,
此時可使用下面的方式:
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()
我們建立一個UDP連線,透過這樣的方式來取得自己的IP,例子中,"1.1.1.1"可以是任何IP,
因為我們並沒有真的要傳送資料,
那...如果要取得真正對外的網路IP呢?
此時我們可利用一些提供這種服務的網站,
例如以下的方式:
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()
當然,上面的例子必須在有連網的情形下執行
沒有留言:
張貼留言