ZNZNCOOP

ip

May 15th, 2014
520
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function open()
  2.   local bOpen, sFreeSide = false, nil
  3.   for n,sSide in pairs(rs.getSides()) do
  4.     if peripheral.getType( sSide ) == "modem" then
  5.       sFreeSide = sSide
  6.       if rednet.isOpen( sSide ) then
  7.         bOpen = true
  8.         break
  9.       end
  10.     end
  11.   end
  12.   if not bOpen then
  13.     if sFreeSide then
  14.       print( "No modem active. Opening "..sFreeSide.." modem" )
  15.       rednet.open( sFreeSide )
  16.       return true
  17.     else
  18.       print( "No modem attached" )
  19.       return false
  20.     end
  21.   end
  22.   return true
  23. end
  24.  
  25. local localIP
  26. local MainGate
  27.  
  28. function getIP(route)
  29.   MainGate=nil
  30.   localIP=nil
  31.   route=route or '*'
  32.   rednet.broadcast('T=1|D='..route..'|S=*|getip')
  33.   local mess,sIP,dIP,gate
  34.   repeat
  35.     mess,sIP,dIP,gate=receive(2)
  36. --    print(mess,' ',sIP)
  37.     if mess=='setip' then
  38.       MainGate=gate
  39.       localIP=dIP
  40.       break
  41.     end
  42.   until not mess
  43.   if localIP then print("IP is ",localIP)
  44.   else print("Can't receive IP.") end
  45.   return localIP
  46. end
  47.  
  48. function send(dIP,mess,T)
  49.   if MainGate then
  50.     rednet.send(MainGate,'T='..(T or 99)..'|D='..dIP..'|S='..localIP..'|'..mess)
  51.   end
  52. end
  53.  
  54. function receive(timeout)
  55.   local gate,mess
  56.   local sIP,dIP
  57.   while true do
  58.     gate,mess=rednet.receive(timeout)
  59. --    print(gate,' ',mess)
  60.     if not gate then return end  --timeout
  61.     if not MainGate or MainGate==gate then
  62.       dIP,sIP,mess=mess:match('T=.-|D=(.-)|S=(.-)|(.*)')
  63.       if mess=='ping' then
  64.         send(sIP,'pong')
  65.       else
  66.         return mess,sIP,dIP,gate
  67.       end
  68.     end
  69.   end
  70. end
  71.  
  72. function sendrec(dIP,mess,timeout)
  73.   send(dIP,mess)
  74.   return receive(timeout or 3)
  75. end
RAW Paste Data