Example usage for java.net DatagramSocket DatagramSocket

List of usage examples for java.net DatagramSocket DatagramSocket

Introduction

In this page you can find the example usage for java.net DatagramSocket DatagramSocket.

Prototype

public DatagramSocket() throws SocketException 

Source Link

Document

Constructs a datagram socket and binds it to any available port on the local host machine.

Usage

From source file:com.all.landownloader.discovery.LanDiscoverySocket.java

public void reply(InetAddress address) throws IllegalArgumentException {
    try {/*w ww.  j  av  a2 s. com*/
        byte[] buf = createPacket(REPLY_MSG);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
        DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();
    } catch (IOException e) {
    }
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Attempts to retrieve the job managers address in the network through an
 * IP broadcast. This method should be called by the task manager.
 * /*from   w  w w . ja v a2 s .c  o  m*/
 * @return the socket address of the job manager in the network
 * @throws DiscoveryException
 *         thrown if the job manager's socket address could not be
 *         discovered
 */
public static InetSocketAddress getJobManagerAddress() throws DiscoveryException {

    final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER);
    final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT);

    InetSocketAddress jobManagerAddress = null;
    DatagramSocket socket = null;

    try {

        final Set<InetAddress> targetAddresses = getBroadcastAddresses();

        if (targetAddresses.isEmpty()) {
            throw new DiscoveryException("Could not find any broadcast addresses available to this host");
        }

        socket = new DatagramSocket();

        LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT);
        socket.setSoTimeout(CLIENTSOCKETTIMEOUT);

        final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE],
                RESPONSE_PACKET_SIZE);

        for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) {

            final DatagramPacket lookupRequest = createJobManagerLookupRequestPacket(magicNumber);

            for (InetAddress broadcast : targetAddresses) {
                lookupRequest.setAddress(broadcast);
                lookupRequest.setPort(discoveryPort);
                LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress());
                socket.send(lookupRequest);
            }

            try {
                socket.receive(responsePacket);
            } catch (SocketTimeoutException ste) {
                LOG.debug("Timeout wainting for discovery reply. Retrying...");
                continue;
            }

            if (!isPacketForUs(responsePacket, magicNumber)) {
                LOG.debug("Received packet which is not destined to this Nephele setup");
                continue;
            }

            final int packetTypeID = getPacketTypeID(responsePacket);
            if (packetTypeID != JM_LOOKUP_REPLY_ID) {
                LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... ");
                continue;
            }

            final int ipcPort = extractIpcPort(responsePacket);

            // Replace port from discovery service with the actual RPC port
            // of the job manager
            if (USE_IPV6) {
                // TODO: No connection possible unless we remove the scope identifier
                if (responsePacket.getAddress() instanceof Inet6Address) {
                    try {
                        jobManagerAddress = new InetSocketAddress(
                                InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort);
                    } catch (UnknownHostException e) {
                        throw new DiscoveryException(StringUtils.stringifyException(e));
                    }
                } else {
                    throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address");
                }
            } else {
                jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort);
            }
            LOG.debug("Discovered job manager at " + jobManagerAddress);
            break;
        }

    } catch (IOException ioe) {
        throw new DiscoveryException(ioe.toString());
    } finally {
        if (socket != null) {
            socket.close();
        }
    }

    if (jobManagerAddress == null) {
        LOG.debug("Unable to discover Jobmanager via IP broadcast");
        throw new DiscoveryException("Unable to discover JobManager via IP broadcast!");
    }

    return jobManagerAddress;
}

From source file:cycronix.ctudp.CTudp.java

public CTudp(String[] arg) {
    String[] chanName = new String[32];
    String defaultChanName = "udpchan";
    String[] csvChanNames = null;
    int ssNum[] = new int[32];
    int defaultPort = 4445;
    double dt[] = new double[32];
    double defaultDT = 0.0;
    int numChan = 0;

    // For communicating with UDP server; we send a "keep alive" heartbeat message to this server
    // and will receive UDP packets from this server
    DatagramSocket clientSocket = null; // This socket will be shared by UDPread and UDPHeartbeatTask classes
    InetAddress udpserverIP = null;
    int udpserverPort = -1;
    int heartbeatPeriod_msec = -1;
    boolean bCSVTest = false; // If the "-csvtest" option has been specified along with the "-udpserver" option, then the heartbeat message itself is a CSV string that can be used for testing CTudp in loopback mode.

    // Optional local UDP server that can be started to serve test data
    int testserverPort = -1;
    int testserverPeriod_msec = -1;

    ////www  .  ja  v a  2  s  . com
    // Argument processing using Apache Commons CLI
    //
    // 1. Setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "Print this message.");
    options.addOption("pack", false,
            "Blocks of data should be packed?  default = " + Boolean.toString(packMode) + ".");
    options.addOption(Option.builder("s").argName("source name").hasArg()
            .desc("Name of source to write packets to; default = \"" + srcName + "\".").build());
    options.addOption(Option.builder("c").argName("channel name").hasArg()
            .desc("Name of channel to write packets to; default = \"" + defaultChanName + "\".").build());
    options.addOption(Option.builder("csplit").argName("channel name(s)").hasArg().desc(
            "Comma-separated list of channel names; split an incoming CSV string into a series of channels with the given names; supported channel name suffixes and their associated data types: .txt (string), .csv or no suffix (numeric), .f32 (32-bit floating point), .f64 (64-bit floating point).")
            .build());
    options.addOption(Option.builder("e").argName("exception val").hasArg().desc(
            "If a CSV string is being parsed (using the -csplit option) and there is an error saving a string component as a floating point value, use this \"exception value\" in its place; default = "
                    + Double.toString(exceptionVal) + ".")
            .build());
    options.addOption(Option.builder("m").argName("multicast address").hasArg()
            .desc("Multicast UDP address (224.0.0.1 to 239.255.255.255).").build());
    options.addOption(Option.builder("p").argName("UDP port").hasArg()
            .desc("Port number to listen for UDP packets on; default = " + Integer.toString(defaultPort) + ".")
            .build());
    options.addOption(Option.builder("d").argName("delta-Time").hasArg()
            .desc("Fixed delta-time (msec) between frames; specify 0 to use arrival-times; default = "
                    + Double.toString(defaultDT) + ".")
            .build());
    options.addOption(Option.builder("f").argName("autoFlush").hasArg().desc(
            "Flush interval (sec); amount of data per zipfile; default = " + Double.toString(autoFlush) + ".")
            .build());
    options.addOption(Option.builder("t").argName("trim-Time").hasArg()
            .desc("Trim (ring-buffer loop) time (sec); specify 0 for indefinite; default = "
                    + Double.toString(trimTime) + ".")
            .build());
    options.addOption(Option.builder("udpserver").argName("IP,port,period_msec").hasArg().desc(
            "Talk to a UDP server; send a periodic keep-alive message to the given IP:port at the specified period and receive packets from this server; not to be used with the \"-p\" option.")
            .build());
    options.addOption(Option.builder("testserver").argName("port,period_msec").hasArg().desc(
            "Start a UDP server on the local machine to serve CSV strings at the specified period with the format specified by the \"-csplit\" option (if no \"-csplit\" option has been specified, a simple text message is output). The test server waits for a message from the client before starting packet flow. This feature can be used along with the \"-udpserver\" option for local/loopback testing (NOTE: make sure the server ports match).")
            .build());
    options.addOption(Option.builder("bps").argName("blocks_per_seg").hasArg()
            .desc("Number of blocks per segment; specify 0 for no segments; default = "
                    + Long.toString(blocksPerSegment) + ".")
            .build());
    options.addOption("w", false, "Split the captured string on white space rather than commas.");
    options.addOption("x", "debug", false, "Debug mode.");

    // 2. Parse command line options
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, arg);
    } catch (ParseException exp) { // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    // 3. Retrieve the command line values
    if (line.hasOption("help")) { // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp("CTudp", options);
        return;
    }

    srcName = line.getOptionValue("s", srcName);

    String chanNameL = line.getOptionValue("c", defaultChanName);
    chanName = chanNameL.split(",");
    numChan = chanName.length;

    if (line.hasOption("csplit")) {
        chanNameL = line.getOptionValue("csplit");
        csvChanNames = chanNameL.split(",");
        if (numChan > 1) {
            System.err.println(
                    "Error: don't use the \"-csplit\" option when receiving packets from multiple UDP ports.");
            System.exit(0);
        }
        // Make sure that the channel names either have no suffix or will end in .txt, .csv, .f32, .f64
        for (int i = 0; i < csvChanNames.length; ++i) {
            int dotIdx = csvChanNames[i].lastIndexOf('.');
            if ((dotIdx > -1) && (!csvChanNames[i].endsWith(".txt")) && (!csvChanNames[i].endsWith(".csv"))
                    && (!csvChanNames[i].endsWith(".f32")) && (!csvChanNames[i].endsWith(".f64"))) {
                System.err.println(
                        "Error: illegal channel name specified in the \"-csplit\" list: " + csvChanNames[i]);
                System.err.println(
                        "\tAccepted channel names: channels with no suffix or with .txt, .csv, .f32 or .f64 suffixes.");
                System.exit(0);
            }
        }
    }

    String exceptionValStr = line.getOptionValue("e", Double.toString(exceptionVal));
    try {
        exceptionVal = Double.parseDouble(exceptionValStr);
    } catch (NumberFormatException nfe) {
        System.err.println("Error parsing the given exception value (\"-e\" flag).");
        System.exit(0);
    }

    multiCast = line.getOptionValue("m", multiCast);

    String nss = line.getOptionValue("p", Integer.toString(defaultPort));
    String[] ssnums = nss.split(",");
    numSock = ssnums.length;
    for (int i = 0; i < numSock; i++)
        ssNum[i] = Integer.parseInt(ssnums[i]);

    String sdt = line.getOptionValue("d", Double.toString(defaultDT));
    String[] ssdt = sdt.split(",");
    for (int i = 0; i < ssdt.length; i++)
        dt[i] = Double.parseDouble(ssdt[i]);

    autoFlush = Double.parseDouble(line.getOptionValue("f", "" + autoFlush));

    trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime)));

    blocksPerSegment = Long.parseLong(line.getOptionValue("bps", Long.toString(blocksPerSegment)));

    if (line.hasOption("pack")) {
        packMode = true;
    }

    bSplitOnWhiteSpace = line.hasOption("w");

    debug = line.hasOption("debug");

    // Parameters when talking to a UDP server
    // Can't specify both "-p" and "-udpserver"
    if (line.hasOption("p") && line.hasOption("udpserver")) {
        System.err.println(
                "Specify either \"-p\" (to listen on the given port(s)) or \"-udpserver\" (to talk to UDP server), not both.");
        System.exit(0);
    }
    if (line.hasOption("udpserver")) {
        String udpserverStr = line.getOptionValue("udpserver");
        // Parse the server,port,period_msec from this string
        String[] udpserverConfigCSV = udpserverStr.split(",");
        if (udpserverConfigCSV.length != 3) {
            System.err.println(
                    "Error: the \"-udpserver\" argument must contain 3 parameters: IP,port,period_msec");
            System.exit(0);
        }
        try {
            udpserverIP = InetAddress.getByName(udpserverConfigCSV[0]);
        } catch (UnknownHostException e) {
            System.err.println("Error processing the \"-udpserver\" server name:\n" + e);
            System.exit(0);
        }
        try {
            udpserverPort = Integer.parseInt(udpserverConfigCSV[1]);
            if (udpserverPort <= 0) {
                throw new Exception("Invalid port number");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-udpserver\" port must be an integer greater than 0.");
            System.exit(0);
        }
        try {
            heartbeatPeriod_msec = Integer.parseInt(udpserverConfigCSV[2]);
            if (heartbeatPeriod_msec <= 0) {
                throw new Exception("Invalid period");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-udpserver\" period_msec must be an integer greater than 0.");
            System.exit(0);
        }
    }

    if (line.hasOption("testserver")) {
        String testserverStr = line.getOptionValue("testserver");
        // Parse the port,period_msec from this string
        String[] testserverConfigCSV = testserverStr.split(",");
        if (testserverConfigCSV.length != 2) {
            System.err
                    .println("Error: the \"-testserver\" argument must contain 2 parameters: port,period_msec");
            System.exit(0);
        }
        try {
            testserverPort = Integer.parseInt(testserverConfigCSV[0]);
            if (testserverPort <= 0) {
                throw new Exception("Invalid port number");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-testserver\" port must be an integer greater than 0.");
            System.exit(0);
        }
        try {
            testserverPeriod_msec = Integer.parseInt(testserverConfigCSV[1]);
            if (testserverPeriod_msec <= 0) {
                throw new Exception("Invalid period");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-testserver\" period_msec must be an integer greater than 0.");
            System.exit(0);
        }
    }

    if (numSock != numChan) {
        System.err.println("Error:  must specify same number of channels and ports!");
        System.exit(0);
    }
    if (multiCast != null && numSock > 1) {
        System.err.println("Error: can only have one multicast socket!");
        System.exit(0);
    }
    if (numSock == 0)
        numSock = 1; // use defaults

    System.err.println("Source name: " + srcName);
    if (udpserverIP == null) {
        for (int i = 0; i < numSock; i++) {
            System.err.println("Channel[" + i + "]: " + chanName[i]);
            System.err.println("UDPport[" + i + "]: " + ssNum[i]);
        }
    }
    if (csvChanNames != null) {
        System.err.println("\nIncoming csv strings will be split into the following channels:");
        for (int i = 0; i < (csvChanNames.length - 1); ++i) {
            System.err.print(csvChanNames[i] + ",");
        }
        System.err.println(csvChanNames[csvChanNames.length - 1]);
    }

    //
    // If user has requested it, start the test UDP server
    //
    if (testserverPort > -1) {
        UDPserver svr = null;
        try {
            svr = new UDPserver(testserverPort, testserverPeriod_msec, csvChanNames);
        } catch (SocketException se) {
            System.err.println("Error: caught exception trying to start test server:\n" + se);
            System.exit(0);
        }
        svr.start();
    }

    //
    // If user requested it, initialize communication with the UDP server
    //
    if (udpserverIP != null) {
        try {
            // This DatagramSocket will be shared by UDPread and UDPHeartbeatTask classes
            clientSocket = new DatagramSocket();
        } catch (SocketException e) {
            System.err.println("Error creating DatagramSocket:\n" + e);
            System.exit(0);
        }
        Timer time = new Timer();
        UDPHeartbeatTask heartbeatTask = new UDPHeartbeatTask(clientSocket, udpserverIP, udpserverPort);
        time.schedule(heartbeatTask, 0, heartbeatPeriod_msec);
    }

    //
    // setup CTwriter
    //
    try {
        ctw = new CTwriter(srcName, trimTime);
        ctw.setBlockMode(packMode, zipMode);
        CTinfo.setDebug(debug);
        ctw.autoSegment(blocksPerSegment);
        autoFlushMillis = (long) (autoFlush * 1000.);
        // ctw.autoFlush(autoFlush);      // auto flush to zip once per interval (sec) of data
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }

    //
    // start a thread for each port
    // if we are talking to a UDP server, there is only 1 instance of UDPread
    //
    if (clientSocket != null) {
        System.err.println("Talk to UDP server at " + udpserverIP + ":" + udpserverPort);
        new UDPread(clientSocket, chanName[0], csvChanNames, dt[0]).start();
    } else {
        for (int i = 0; i < numSock; i++) {
            System.err.println("start thread for port: " + ssNum[i] + ", chan: " + chanName[i]);
            new UDPread(ssNum[i], chanName[i], csvChanNames, dt[i]).start();
        }
    }
}

From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java

private final int handleFindBindingAddress(InetAddress currentBindIP, StringBuilder sReply, int numLoops) {
    if (currentBindIP == null) {
        addReply(sReply, CHAR_BAD, "!Bind IP null!", new String[] { "" + currentBindIP });
        return STATUS_ID_BAD;
    }//from w  ww  .  ja va2  s . c  o  m

    int newStatusID = STATUS_ID_OK;

    Map<String, BindableInterface> mapBindableInterfaces = new HashMap<String, BindableInterface>();

    BindableInterface newBind = null;

    String s;

    // The "Any" field is equivalent to 0.0.0.0 in dotted-quad notation, which is unbound.
    // "Loopback" is 127.0.0.1, which is bound when Vuze can't bind to
    // user specified interface (ie. kill switched)
    if (currentBindIP.isAnyLocalAddress()) {
        addReply(sReply, CHAR_WARN, "vpnhelper.vuze.unbound");
    } else if (currentBindIP.isLoopbackAddress()) {
        addReply(sReply, CHAR_BAD, "vpnhelper.vuze.loopback");
    } else {
        // bound
        boolean isGoodExistingBind = matchesVPNIP(currentBindIP, null);
        if (isGoodExistingBind) {
            String niName = "Unknown Interface";
            try {
                NetworkInterface networkInterface = NetUtils.getByInetAddress(currentBindIP);
                niName = networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")";
            } catch (Throwable e) {
            }
            addReply(sReply, CHAR_GOOD, "vpnhelper.bound.good", new String[] { "" + currentBindIP, niName });
            vpnIP = currentBindIP;
        } else {
            addReply(sReply, CHAR_BAD, "vpnhelper.bound.bad", new String[] { "" + currentBindIP });
        }
    }

    try {
        boolean foundExistingVPNIP = false;
        NetworkAdmin networkAdmin = NetworkAdmin.getSingleton();

        // Find a bindable address that starts with 10.
        InetAddress[] bindableAddresses = networkAdmin.getBindableAddresses();

        for (InetAddress bindableAddress : bindableAddresses) {
            if (matchesVPNIP(bindableAddress, null)) {
                String hostAddress = bindableAddress.getHostAddress();
                BindableInterface bi = mapBindableInterfaces.get(hostAddress);
                if (bi == null) {
                    bi = new BindableInterface(bindableAddress, NetUtils.getByInetAddress(bindableAddress));
                    mapBindableInterfaces.put(hostAddress, bi);
                    if (!foundExistingVPNIP && bindableAddress.equals(vpnIP)) {
                        foundExistingVPNIP = true;
                    }
                }
            }
        }

        // Find a Network Interface that has an address that starts with 10.
        NetworkAdminNetworkInterface[] interfaces = networkAdmin.getInterfaces();

        /* Test reverse *
        for (int i = 0; i < interfaces.length / 2; i++) {
           NetworkAdminNetworkInterface temp = interfaces[i];
           interfaces[i] = interfaces[interfaces.length - i - 1];
           interfaces[interfaces.length - i - 1] = temp;
        }
        /**/
        for (NetworkAdminNetworkInterface networkAdminInterface : interfaces) {
            NetworkAdminNetworkInterfaceAddress[] addresses = networkAdminInterface.getAddresses();
            for (NetworkAdminNetworkInterfaceAddress a : addresses) {
                InetAddress address = a.getAddress();
                if (address instanceof Inet4Address) {
                    if (matchesVPNIP(address, null)) {
                        String hostAddress = address.getHostAddress();
                        BindableInterface bi = mapBindableInterfaces.get(hostAddress);
                        if (bi == null) {
                            bi = new BindableInterface(address,
                                    NetUtils.getByName(networkAdminInterface.getName()));
                            mapBindableInterfaces.put(hostAddress, bi);
                            if (!foundExistingVPNIP && address.equals(vpnIP)) {
                                foundExistingVPNIP = true;
                            }
                        }
                    }
                }
            }
        }

        if (vpnIP != null && !foundExistingVPNIP) {
            String niName = "Unknown Interface";
            try {
                NetworkInterface networkInterface = NetUtils.getByInetAddress(currentBindIP);
                niName = networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")";
            } catch (Throwable e) {
            }
            addReply(sReply, CHAR_WARN, "vpnhelper.existing.not.found",
                    new String[] { "" + currentBindIP, niName });

            if (numLoops == 0) {
                try {
                    Field fldLastNICheck = NetUtils.class.getDeclaredField("last_ni_check");
                    fldLastNICheck.setAccessible(true);
                    fldLastNICheck.set(null, Long.valueOf(-1));
                    return handleFindBindingAddress(currentBindIP, sReply, ++numLoops);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        }

        BindableInterface[] array = mapBindableInterfaces.values().toArray(new BindableInterface[0]);
        Arrays.sort(array);

        for (BindableInterface bi : array) {
            if (!bi.isValidPrefixLength(minSubnetMaskBitCount)) {
                addReply(sReply, CHAR_WARN, "vpnhelper.submask.too.broad",
                        new String[] { "" + bi.address,
                                bi.networkInterface == null ? "null"
                                        : bi.networkInterface.getName() + " ("
                                                + bi.networkInterface.getDisplayName() + ")",
                                "" + bi.networkPrefixLength, "" + minSubnetMaskBitCount });
            } else if (bi.canReach) {
                addReply(sReply, CHAR_GOOD, "vpnhelper.found.bindable.vpn",
                        new String[] { "" + bi.address,
                                bi.networkInterface == null ? "null"
                                        : bi.networkInterface.getName() + " ("
                                                + bi.networkInterface.getDisplayName() + ")" });
            } else {
                addReply(sReply, CHAR_WARN, "vpnhelper.not.reachable",
                        new String[] { "" + bi.address,
                                bi.networkInterface == null ? "null"
                                        : bi.networkInterface.getName() + " ("
                                                + bi.networkInterface.getDisplayName() + ")" });
            }
            PluginVPNHelper.log("subnet: " + bi.networkPrefixLength + "; Score: " + bi.score);
        }
        newBind = array.length > 0 && array[0].canReach && array[0].isValidPrefixLength(minSubnetMaskBitCount)
                ? array[0]
                : null;

        InetAddress localAddress = null;

        // Check if default routing goes through 10.*, by connecting to address
        // via socket.  Address doesn't need to be reachable, just routable.
        // This works on Windows, but on Mac returns a wildcard address
        DatagramSocket socket = new DatagramSocket();
        try {
            socket.connect(testSocketAddress, 0);
            localAddress = socket.getLocalAddress();
        } finally {
            socket.close();
        }

        if (localAddress != null && !localAddress.isAnyLocalAddress()) {
            NetworkInterface networkInterface = NetUtils.getByInetAddress(localAddress);

            s = texts.getLocalisedMessageText("vpnhelper.nonvuze.probable.route",
                    new String[] { "" + localAddress, networkInterface == null ? "null"
                            : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

            if ((localAddress instanceof Inet4Address) && matchesVPNIP(localAddress, networkInterface)) {

                if (newBind == null) {

                    int networkPrefixLength = getNetworkPrefixLength(networkInterface, localAddress);
                    if (networkPrefixLength >= 0 && networkPrefixLength < minSubnetMaskBitCount) {
                        s = null;
                        addReply(sReply, CHAR_WARN, "vpnhelper.nonvuze.submask.too.broad",
                                new String[] { "" + localAddress,
                                        networkInterface == null ? "null"
                                                : networkInterface.getName() + " ("
                                                        + networkInterface.getDisplayName() + ")",
                                        "" + networkPrefixLength, "" + minSubnetMaskBitCount });
                    } else if (!canReach(localAddress)) {
                        addReply(sReply, CHAR_WARN, "vpnhelper.not.reachable",
                                new String[] { "" + localAddress,
                                        networkInterface == null ? "null"
                                                : networkInterface.getName() + " ("
                                                        + networkInterface.getDisplayName() + ")" });
                    } else {
                        newBind = new BindableInterface(localAddress, networkInterface);

                        s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("vpnhelper.assuming.vpn");
                    }
                } else if (localAddress.equals(newBind.address)) {
                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("vpnhelper.same.address");
                } else {
                    // Vuze not bound. We already found a boundable address, but it's not this one
                    /* Possibly good case:
                     * - Vuze: unbound
                     * - Found Bindable: 10.100.1.6
                     * - Default Routing: 10.255.1.1
                     * -> Split network
                     */
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s = CHAR_WARN + " " + s + " "
                            + texts.getLocalisedMessageText("vpnhelper.not.same.future.address") + " "
                            + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting") + " "
                            + texts.getLocalisedMessageText(
                                    "default.routing.not.vpn.network.splitting.unbound");
                }

                if (s != null) {
                    addLiteralReply(sReply, s);
                }

            } else {
                s = CHAR_WARN + " " + s;
                if (!currentBindIP.isLoopbackAddress()) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }

                if (newBind == null) {
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s += " " + texts
                            .getLocalisedMessageText("default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "vpnhelper.nat.error", new String[] { e.toString() });
    }

    if (newBind == null) {
        addReply(sReply, CHAR_BAD, "vpnhelper.vpn.ip.detect.fail");

        String configBindIP = config.getCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP);

        if (configBindIP != null && configBindIP.length() > 0) {
            addReply(sReply, CHAR_WARN,
                    "vpnhelper" + (currentBindIP.isLoopbackAddress() ? ".existing.bind.kept.loopback"
                            : ".existing.bind.kept"),
                    new String[] { configBindIP });

            if (currentBindIP.isLoopbackAddress()) {
                if (numLoops == 0) {
                    try {
                        Field fldLastNICheck = NetUtils.class.getDeclaredField("last_ni_check");
                        fldLastNICheck.setAccessible(true);
                        fldLastNICheck.set(null, Long.valueOf(-1));
                        return handleFindBindingAddress(currentBindIP, sReply, ++numLoops);
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            }
        }

        return STATUS_ID_BAD;
    }

    rebindNetworkInterface(newBind.networkInterface, newBind.address, sReply);
    return newStatusID;
}

From source file:org.openchaos.android.fooping.service.PingService.java

private void sendMessage(final JSONObject json) {
    boolean encrypt = prefs.getBoolean("SendAES", false);
    boolean compress = prefs.getBoolean("SendGZIP", false);
    String exchangeHost = prefs.getString("ExchangeHost", null);
    int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));

    if (encrypt) {
        if (skeySpec == null) {
            try {
                skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256")
                        .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();/*from  w  w w.j  a  va2 s  .  co m*/
            }
        }

        if (cipher == null) {
            try {
                cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();
            }
        }

        if (skeySpec == null || cipher == null) {
            Log.e(tag, "Encryption requested but not available");
            throw new AssertionError();
        }
    }

    if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) {
        Log.e(tag, "Invalid server name or port");
        throw new AssertionError();
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CipherOutputStream cos = null;
        GZIPOutputStream zos = null;

        // TODO: send protocol header to signal compression & encryption

        if (encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            cos = new CipherOutputStream(baos, cipher);

            // write iv block
            baos.write(cipher.getIV());
        }

        final byte[] message = new JSONArray().put(json).toString().getBytes();

        if (compress) {
            zos = new GZIPOutputStream((encrypt) ? (cos) : (baos));
            zos.write(message);
            zos.finish();
            zos.close();
            if (encrypt) {
                cos.close();
            }
        } else if (encrypt) {
            cos.write(message);
            cos.close();
        } else {
            baos.write(message);
        }

        baos.flush();
        final byte[] output = baos.toByteArray();
        baos.close();

        // path MTU is the actual limit here, not only local MTU
        // TODO: make packet fragmentable (clear DF flag)
        if (output.length > 1500) {
            Log.w(tag, "Message probably too long: " + output.length + " bytes");
        }

        DatagramSocket socket = new DatagramSocket();
        // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
        socket.send(
                new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort));
        socket.close();
        Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)");
    } catch (Exception e) {
        Log.e(tag, e.toString());
        e.printStackTrace();
    }
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java

private int dtnResourcesRequest(Node node) throws WSIAdapterException, IOException {
    int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return.
    String proxyAddress = getProxyAddress(node);
    if (proxyAddress != null) {
        int packetID = UNDEFINED_COAP_MESSAGE_ID;
        do { //while loop to avoid a packetID that exists in the array that is to be ignored!
            packetID = random.nextInt(65535) + 1;
        } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID))
                || packetID == UNDEFINED_COAP_MESSAGE_ID);

        String msgString = Integer.toString(packetID) + "#" + node.getId() + "#" + RESOURCE_REQ + "#wkc";
        byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE];
        msgBytes = msgString.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length,
                InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT);
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.send(sendPacket);//from   w ww.ja va2s . co m
        clientSocket.close();
        requestMsgId = packetID;
        logger.info("Sent Request: " + msgString);
    } else {
        logger.warn("No available proxy for Node " + node.getId() + " is found");
        throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found");
    }
    return requestMsgId;
}

From source file:com.vuze.plugin.azVPN_PIA.Checker.java

private int handleBound(InetAddress bindIP, StringBuilder sReply) {
    int newStatusID = STATUS_ID_OK;

    String s;/*from ww  w  .j  a va  2 s  . c o m*/
    boolean isGoodExistingBind = matchesVPNIP(bindIP);
    if (isGoodExistingBind) {
        String niName = "Unknown Interface";
        try {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(bindIP);
            niName = networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")";
        } catch (Throwable e) {
        }
        addReply(sReply, CHAR_GOOD, "pia.bound.good", new String[] { "" + bindIP, niName });
        vpnIP = bindIP;
    } else {
        addReply(sReply, CHAR_BAD, "pia.bound.bad", new String[] { "" + bindIP });
        newStatusID = STATUS_ID_BAD;
    }

    try {
        // Check if default routing goes through 10.*, by connecting to address
        // via socket.  Address doesn't need to be reachable, just routable.
        // This works on Windows (in some cases), but on Mac returns a wildcard 
        // address
        DatagramSocket socket = new DatagramSocket();
        socket.connect(testSocketAddress, 0);
        InetAddress localAddress = socket.getLocalAddress();
        socket.close();

        if (!localAddress.isAnyLocalAddress()) {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress);

            s = texts.getLocalisedMessageText("pia.nonvuze.probable.route", new String[] { "" + localAddress,
                    networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });
            char replyChar = ' ';

            if ((localAddress instanceof Inet4Address) && matchesVPNIP(localAddress)) {

                if (localAddress.equals(bindIP)) {
                    replyChar = isGoodExistingBind ? CHAR_GOOD : CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("pia.same.as.vuze");
                } else {
                    // Vuze is bound, default routing goes somewhere else
                    // This is ok, since Vuze will not accept incoming from "somewhere else"
                    // We'll warn, but not update the status id

                    replyChar = CHAR_WARN;
                    s += " " + texts.getLocalisedMessageText("pia.not.same");

                    if (isGoodExistingBind) {
                        s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                    }
                }

                addLiteralReply(sReply, replyChar + " " + s);

                if (!isGoodExistingBind && rebindNetworkInterface) {
                    rebindNetworkInterface(networkInterface, localAddress, sReply);
                    // Should we redo test?
                }

            } else {
                // Vuze is bound, default routing goes to somewhere else.
                // Probably network splitting
                replyChar = isGoodExistingBind ? CHAR_WARN : CHAR_BAD;
                if (isGoodExistingBind) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }
                addLiteralReply(sReply, replyChar + " " + s);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return newStatusID;
}

From source file:com.clustercontrol.notify.util.SendSyslog.java

private void sendUdpMsg(InetAddress ipAddress, int port, String msg) throws IOException {
    DatagramSocket soc = null;/* w  w w  . j ava  2s  . com*/
    try {
        // ??????
        soc = new DatagramSocket(); // ??
        DatagramPacket sendPacket = null; // 

        sendPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, ipAddress, port);
        soc.send(sendPacket);
    } finally {
        if (soc != null) {
            soc.close();
        }
    }
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java

private int dtnObservationRequest(Node node, Resource resource) throws VitroGatewayException, IOException {
    int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return.
    String proxyAddress = getProxyAddress(node);
    if (proxyAddress != null) {
        String moteUriResource = "";
        if (MoteResource.containsValue(resource)) {
            //moteUriResource += MoteResource.getMoteUriResource(resource);
            String theResourceName = MoteResource.getMoteUriResource(resource);
            if (theResourceName == null) {
                logger.error("unsupported resource");
                return UNDEFINED_COAP_MESSAGE_ID;
            }/* ww  w.  ja v a2 s  .  co m*/
            // FOR TCS adapter, we prefer the TEMPERATURE_TCS
            // FOR WLAB and HAI we prefer the TEMPERATURE_ALT
            // we do this check because the getMoteUriResource is making a reverse lookup in the hashmap (where two keys point to the same resource)
            if (theResourceName.compareToIgnoreCase(MoteResource.TEMPERATURE_TCS) == 0) {
                theResourceName = MoteResource.TEMPERATURE_ALT;
            }
            moteUriResource += theResourceName;

            int packetID = UNDEFINED_COAP_MESSAGE_ID;
            do { //while loop to avoid a packetID that exists in the array that is to be ignored!
                packetID = random.nextInt(65535) + 1;
            } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID))
                    || packetID == UNDEFINED_COAP_MESSAGE_ID);

            String msgString = packetID + "#" + node.getId() + "#" + RESOURCE_REQ + "#" + moteUriResource;
            byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE];
            msgBytes = msgString.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length,
                    InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT);
            DatagramSocket clientSocket = new DatagramSocket();
            clientSocket.send(sendPacket);
            clientSocket.close();
            requestMsgId = packetID;
            logger.info("Sent Request: " + msgString);
        } else {
            logger.warn("No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
            throw new WSIAdapterException(
                    "No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
        }
    } else {
        logger.warn("No available proxy for Node " + node.getId() + " is found");
        throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found");
    }
    return requestMsgId;
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoapHAI.java

private int dtnObservationRequest(Node node, Resource resource) throws VitroGatewayException, IOException {
    int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return.
    String proxyAddress = getProxyAddress(node);
    if (proxyAddress != null) {
        String moteUriResource = "";
        if (MoteResource.containsValue(resource)) {
            //moteUriResource += MoteResource.getMoteUriResource(resource);
            String theResourceName = MoteResource.getMoteUriResource(resource);
            if (theResourceName == null) {
                logger.error("unsupported resource");
                return UNDEFINED_COAP_MESSAGE_ID;
            }/*  ww  w .  j ava2s  . c  om*/
            // FOR TCS adapter, we prefer the TEMPERATURE_TCS
            // FOR WLAB and HAI we prefer the TEMPERATURE_ALT
            // we do this check because the getMoteUriResource is making a reverse lookup in the hashmap (where two keys point to the same resource)
            if (theResourceName.compareToIgnoreCase(MoteResource.TEMPERATURE_TCS) == 0) {
                theResourceName = MoteResource.TEMPERATURE_ALT;
            }
            moteUriResource += theResourceName;
            int packetID = UNDEFINED_COAP_MESSAGE_ID;
            do { //while loop to avoid a packetID that exists in the array that is to be ignored!
                packetID = random.nextInt(65535) + 1;
            } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID))
                    || packetID == UNDEFINED_COAP_MESSAGE_ID);

            String msgString = packetID + "#" + node.getId() + "#" + RESOURCE_REQ + "#" + moteUriResource;
            byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE];
            msgBytes = msgString.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length,
                    InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT);
            DatagramSocket clientSocket = new DatagramSocket();
            clientSocket.send(sendPacket);
            clientSocket.close();
            requestMsgId = packetID;
            logger.info("Sent Request: " + msgString);
        } else {
            logger.warn("No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
            throw new WSIAdapterException(
                    "No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
        }
    } else {
        logger.warn("No available proxy for Node " + node.getId() + " is found");
        throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found");
    }
    return requestMsgId;
}