Example usage for java.net DatagramSocket getLocalPort

List of usage examples for java.net DatagramSocket getLocalPort

Introduction

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

Prototype

public int getLocalPort() 

Source Link

Document

Returns the port number on the local host to which this socket is bound.

Usage

From source file:Main.java

public static void main(String args[]) {
    try {//from  w  w  w.  jav a  2 s  .  co  m

        InetAddress ia = InetAddress.getByName("www.java2s.com");

        DatagramSocket ds = new DatagramSocket();

        byte buffer[] = "hello".getBytes();
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, 80);

        // Send the datagram packet
        ds.send(dp);

        System.out.println(ds.getLocalPort());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sourceforge.vulcan.ant.receiver.UdpEventSource.java

protected DatagramSocket openSocket() {
    try {//from  w  w w .  j  a v  a  2 s  . c om
        final SocketAddress addr = new InetSocketAddress(listenAddress, port);
        final DatagramSocket socket = new DatagramSocket(addr);
        socket.setSoTimeout(timeout);
        this.port = socket.getLocalPort();
        return socket;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.jmeter.JMeter.java

private static void waitForSignals(final List<JMeterEngine> engines, DatagramSocket socket) {
    byte[] buf = new byte[80];
    System.out.println(//from  www.  j av a2 s  .c o  m
            "Waiting for possible Shutdown/StopTestNow/Heapdump message on port " + socket.getLocalPort());
    DatagramPacket request = new DatagramPacket(buf, buf.length);
    try {
        while (true) {
            socket.receive(request);
            InetAddress address = request.getAddress();
            // Only accept commands from the local host
            if (address.isLoopbackAddress()) {
                String command = new String(request.getData(), request.getOffset(), request.getLength(),
                        "ASCII");
                System.out.println("Command: " + command + " received from " + address);
                log.info("Command: " + command + " received from " + address);
                if (command.equals("StopTestNow")) {
                    for (JMeterEngine engine : engines) {
                        engine.stopTest(true);
                    }
                } else if (command.equals("Shutdown")) {
                    for (JMeterEngine engine : engines) {
                        engine.stopTest(false);
                    }
                } else if (command.equals("HeapDump")) {
                    HeapDumper.dumpHeap();
                } else {
                    System.out.println("Command: " + command + " not recognised ");
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        socket.close();
    }
}

From source file:com.clustercontrol.poller.impl.UdpTransportMappingImpl.java

@Override
public UdpAddress getListenAddress() {
    UdpAddress actualListenAddress = null;
    DatagramSocket socketCopy = socket;
    if (socketCopy != null) {
        actualListenAddress = new UdpAddress(socketCopy.getInetAddress(), socketCopy.getLocalPort());
    }/*from w  w w.j  a  v  a 2s.c  om*/
    return actualListenAddress;
}

From source file:org.lockss.protocol.LcapDatagramComm.java

protected void updateInStats(LockssReceivedDatagram ld) throws ProtocolException {
    boolean mcast = ld.isMulticast();
    if (mcast && didISend(ld)) {
        // We receive all the multicast packets we send; don't count them in
        // receive statistics.
        // This does not work when running multiple daemons on one machine,
        // as the packets from all the instances have the same source addr
        // (which is probably not the local identity addr).
        return;//ww  w.  ja  v  a  2  s . c  o  m
    }
    LcapSocket lsock = ld.getReceiveSocket();
    DatagramSocket sock = lsock.getSocket();
    updateStats(ld, sock.getLocalPort(), true, mcast);
}

From source file:lockstep.LockstepServer.java

/**
 * Implements the handshake protocol server side, setting up the UDP 
 * connection, queues and threads for a specific client.
 * To be run in parallel threads, one for each client, as they need
 * to synchronize to correctly setup the lockstep protocol.
 * It signals success through a latch or failure through interruption to the
 * server thread./*from   w w w.j av  a 2 s .com*/
 * 
 * @param tcpSocket Connection with the client, to be used in handshake only
 * @param firstFrameNumber Frame number to initialize the lockstep protocol
 * @param barrier Used for synchronization with concurrent handshake sessions
 * @param latch Used to signal the successful completion of the handshake session.
 * @param server Used to signal failure of the handshake sessions, via interruption.
 */
private void serverHandshakeProtocol(Socket tcpSocket, int firstFrameNumber, CyclicBarrier barrier,
        CountDownLatch latch, LockstepServer server) {
    try (ObjectOutputStream oout = new ObjectOutputStream(tcpSocket.getOutputStream());) {
        oout.flush();
        try (ObjectInputStream oin = new ObjectInputStream(tcpSocket.getInputStream());) {
            //Receive hello message from client and reply
            LOG.info("Waiting an hello from " + tcpSocket.getInetAddress().getHostAddress());
            oout.flush();
            ClientHello hello = (ClientHello) oin.readObject();
            LOG.info("Received an hello from " + tcpSocket.getInetAddress().getHostAddress());
            DatagramSocket udpSocket = new DatagramSocket();
            openSockets.add(udpSocket);
            InetSocketAddress clientUDPAddress = new InetSocketAddress(
                    tcpSocket.getInetAddress().getHostAddress(), hello.clientUDPPort);
            udpSocket.connect(clientUDPAddress);

            int assignedClientID;
            do {
                assignedClientID = (new Random()).nextInt(100000) + 10000;
            } while (!this.clientIDs.add(assignedClientID));

            LOG.info("Assigned hostID " + assignedClientID + " to "
                    + tcpSocket.getInetAddress().getHostAddress() + ", sending helloReply");
            ServerHelloReply helloReply = new ServerHelloReply(udpSocket.getLocalPort(), assignedClientID,
                    clientsNumber, firstFrameNumber);
            oout.writeObject(helloReply);

            ConcurrentHashMap<Integer, TransmissionQueue> clientTransmissionFrameQueues = new ConcurrentHashMap<>();
            this.transmissionFrameQueueTree.put(assignedClientID, clientTransmissionFrameQueues);

            ACKSet clientAckQueue = new ACKSet();
            ackQueues.put(assignedClientID, clientAckQueue);

            clientReceiveSetup(assignedClientID, udpSocket, firstFrameNumber, clientTransmissionFrameQueues);

            barrier.await();

            //Send second reply
            ClientsAnnouncement announcement = new ClientsAnnouncement();
            announcement.clientIDs = ArrayUtils.toPrimitive(this.clientIDs.toArray(new Integer[0]));
            oout.writeObject(announcement);

            clientTransmissionSetup(assignedClientID, firstFrameNumber, udpSocket,
                    clientTransmissionFrameQueues);

            //Wait for other handshakes to reach final step
            barrier.await();
            oout.writeObject(new SimulationStart());

            //Continue with execution
            latch.countDown();
        }
    } catch (IOException | ClassNotFoundException ioEx) {
        LOG.fatal("Exception at handshake with client");
        LOG.fatal(ioEx);
        server.interrupt();
    } catch (InterruptedException | BrokenBarrierException inEx) {
        //Interruptions come from failure in parallel handshake sessions, and signal termination
    }
}

From source file:com.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();//from   ww w . jav  a2  s  . com

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}

From source file:com.lfv.yada.net.client.ClientNetworkManager.java

public ClientNetworkManager(int terminalId, ClientBundle bundle, SocketAddress serverSocketAddr,
        SocketAddress localhostBindSocketAddr, SocketAddress multicastSocketAddr, int multicastTTL,
        TerminalProperties properties) throws IOException {

    // Create a logger for this class
    log = LogFactory.getLog(getClass());

    // Load terminal properties
    this.properties = properties;

    // Setup stuff
    this.terminalId = terminalId;
    this.bundle = bundle;
    this.serverSocketAddr = new SocketAddress(serverSocketAddr);

    // Resolve local host address
    InetAddress localHost = getLocalHostFix();
    if (localHost == null) {
        localHost = InetAddress.getLocalHost();
        if (localHost == null)
            throw new UnknownHostException("Could not resolve ip address of localhost");
    }//ww  w. j  a  v  a2 s.c  o m

    // The socket to be used for sending and receiving unicast packets
    DatagramSocket usocket;
    if (localhostBindSocketAddr.getAddress() == 0)
        usocket = new DatagramSocket();
    else
        usocket = new DatagramSocket(localhostBindSocketAddr.getPort(),
                localhostBindSocketAddr.getInetAddress());

    // The multicast socket
    InetAddress maddr = multicastSocketAddr.getInetAddress();
    int mport = multicastSocketAddr.getPort();
    MulticastSocket msocket = null;

    multicastAvailable = (maddr != null && mport > 0);
    if (multicastAvailable) {
        msocket = new MulticastSocket(mport);
        try {
            msocket.joinGroup(maddr);
            msocket.setTimeToLive(multicastTTL);
        } catch (SocketException ex) {
            log.warn("!!!");
            log.warn("!!! Unable to create multicast socket! Multicasting has been disabled!");
            log.warn("!!! On linux systems a default gateway must be defined, try:");
            log.warn("!!! > route add default gw <some_ip_address>");
            log.warn("!!!");
            msocket = null;
            multicastAvailable = false;
        }
    } else
        log.warn("No multicast address or port defined, multicasting has been disabled!");

    // Store the local unicast ip address and port
    localSocketAddr = new SocketAddress(localHost, usocket.getLocalPort());

    // Create a receiver and a sender (send/recv must use the same port number)
    receiver = new ClientPacketReceiver(terminalId, usocket, msocket);
    sender = new ClientPacketSender(usocket, msocket, multicastSocketAddr);

    // Create a transaction mananger
    transactionManager = new TransactionManager(sender);
    receiver.setControlPacketDispatcher(transactionManager);
    receiver.setSendPacketDispatcher(sender);

    // Create a timer for handling pings
    timer = new Timer("Snetworkmanager", true);

    // Initialize packet pool
    PacketPool.getPool();

    // Setup request handlers
    transactionManager.setRequestHandler(Packet.SESSION, new SessionRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.UPDATE, new UpdateRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INFO, new InfoRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.ISA, new IsaRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.CONNECT, new ConnectRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INITIATE, new InitiateRequestPacketHandler());
}