Posted by Anonymous on Thu 23 Aug 16:58
report abuse | download | new post
- // Returns the local machine's IP address as a dotted-quad string, by
- // sending myself a UDP packet with a unique string. This function
- // UDP-broadcasts, otherwise the remote address of a received packet
- // is 127.0.0.1.
- function findMyIP() {
- var sock = new java.net.DatagramSocket();
- var sendSock = new java.net.DatagramSocket();
- var secret = java.util.UUID.randomUUID().toString();
- var place = new java.util.Hashtable(1); // thread-safe
- // Receive UDP packet with secret in looping background thread.
- spawn(function() {
- var sb = new java.lang.StringBuffer();
- sb.setLength(secret.length);
- while(true) {
- var p = new java.net.DatagramPacket(new java.lang.String(sb.toString()).getBytes(), secret.length);
- sock.receive(p);
- if (new java.lang.String(p.getData()) == secret) {
- place.put("ip", p.getAddress().getHostAddress());
- break;
- }
- }
- });
- // Send packets with secret until receiver thread puts IP into table.
- while(true) {
- var p = new java.net.DatagramPacket(new java.lang.String(secret).getBytes(),
- secret.length,
- java.net.InetAddress.getByName("255.255.255.255"),
- sock.getLocalPort());
- sendSock.send(p);
- app.log("Waiting for my IP...");
- java.lang.Thread.sleep(500);
- var myIP = place.get("ip");
- if (myIP != null) {
- return myIP;
- }
- }
- }
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.