Example usage for java.net DatagramPacket getPort

List of usage examples for java.net DatagramPacket getPort

Introduction

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

Prototype

public synchronized int getPort() 

Source Link

Document

Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received.

Usage

From source file:net.pms.network.UPNPHelper.java

/**
 * Starts up two threads: one to broadcast UPnP ALIVE messages and another
 * to listen for responses. /*  ww  w .ja  va  2s  . co m*/
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void listen() throws IOException {
    Runnable rAlive = new Runnable() {
        @Override
        public void run() {
            int delay = 10000;

            while (true) {
                sleep(delay);
                sendAlive();

                // The first delay for sending an ALIVE message is 10 seconds,
                // the second delay is for 20 seconds. From then on, all other
                // delays are for 180 seconds.
                switch (delay) {
                case 10000:
                    delay = 20000;
                    break;
                case 20000:
                    delay = 180000;
                    break;
                }
            }
        }
    };

    aliveThread = new Thread(rAlive, "UPNP-AliveMessageSender");
    aliveThread.start();

    Runnable r = new Runnable() {
        @Override
        public void run() {
            boolean bindErrorReported = false;

            while (true) {
                MulticastSocket multicastSocket = null;

                try {
                    // Use configurable source port as per http://code.google.com/p/ps3mediaserver/issues/detail?id=1166
                    multicastSocket = new MulticastSocket(configuration.getUpnpPort());

                    if (bindErrorReported) {
                        logger.warn(
                                "Finally, acquiring port " + configuration.getUpnpPort() + " was successful!");
                    }

                    NetworkInterface ni = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName();

                    try {
                        // Setting the network interface will throw a SocketException on Mac OSX
                        // with Java 1.6.0_45 or higher, but if we don't do it some Windows
                        // configurations will not listen at all.
                        if (ni != null) {
                            multicastSocket.setNetworkInterface(ni);
                        } else if (PMS.get().getServer().getNetworkInterface() != null) {
                            multicastSocket.setNetworkInterface(PMS.get().getServer().getNetworkInterface());
                            logger.trace("Setting multicast network interface: "
                                    + PMS.get().getServer().getNetworkInterface());
                        }
                    } catch (SocketException e) {
                        // Not setting the network interface will work just fine on Mac OSX.
                    }

                    multicastSocket.setTimeToLive(4);
                    multicastSocket.setReuseAddress(true);
                    InetAddress upnpAddress = getUPNPAddress();
                    multicastSocket.joinGroup(upnpAddress);

                    while (true) {
                        byte[] buf = new byte[1024];
                        DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
                        multicastSocket.receive(receivePacket);

                        String s = new String(receivePacket.getData());

                        InetAddress address = receivePacket.getAddress();

                        if (s.startsWith("M-SEARCH")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            if (configuration.getIpFiltering().allowed(address)) {
                                logger.trace(
                                        "Receiving a M-SEARCH from [" + remoteAddr + ":" + remotePort + "]");

                                if (StringUtils.indexOf(s,
                                        "urn:schemas-upnp-org:service:ContentDirectory:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:service:ContentDirectory:1");
                                }

                                if (StringUtils.indexOf(s, "upnp:rootdevice") > 0) {
                                    sendDiscover(remoteAddr, remotePort, "upnp:rootdevice");
                                }

                                if (StringUtils.indexOf(s, "urn:schemas-upnp-org:device:MediaServer:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, "ssdp:all") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, PMS.get().usn()) > 0) {
                                    sendDiscover(remoteAddr, remotePort, PMS.get().usn());
                                }
                            }
                        } else if (s.startsWith("NOTIFY")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            logger.trace("Receiving a NOTIFY from [" + remoteAddr + ":" + remotePort + "]");
                        }
                    }
                } catch (BindException e) {
                    if (!bindErrorReported) {
                        logger.error("Unable to bind to " + configuration.getUpnpPort()
                                + ", which means that PMS will not automatically appear on your renderer! "
                                + "This usually means that another program occupies the port. Please "
                                + "stop the other program and free up the port. "
                                + "PMS will keep trying to bind to it...[" + e.getMessage() + "]");
                    }

                    bindErrorReported = true;
                    sleep(5000);
                } catch (IOException e) {
                    logger.error("UPNP network exception", e);
                    sleep(1000);
                } finally {
                    if (multicastSocket != null) {
                        // Clean up the multicast socket nicely
                        try {
                            InetAddress upnpAddress = getUPNPAddress();
                            multicastSocket.leaveGroup(upnpAddress);
                        } catch (IOException e) {
                        }

                        multicastSocket.disconnect();
                        multicastSocket.close();
                    }
                }
            }
        }
    };

    listenerThread = new Thread(r, "UPNPHelper");
    listenerThread.start();
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPAckPacket.java

/***
 * Creates an acknowledgement packet based from a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>/*from  www  .jav  a 2 s .com*/
 * @param datagram  The datagram containing the received acknowledgement.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         acknowledgement packet.
 ***/
TFTPAckPacket(DatagramPacket datagram) throws TFTPPacketException {
    super(TFTPPacket.ACKNOWLEDGEMENT, datagram.getAddress(), datagram.getPort());
    byte[] data;

    data = datagram.getData();

    if (getType() != data[1])
        throw new TFTPPacketException("TFTP operator code does not match type.");

    _blockNumber = (((data[2] & 0xff) << 8) | (data[3] & 0xff));
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPErrorPacket.java

/***
 * Creates an error packet based from a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>/*from  ww  w  .j  av a 2s .com*/
 * @param datagram  The datagram containing the received error.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         error packet.
 ***/
TFTPErrorPacket(DatagramPacket datagram) throws TFTPPacketException {
    super(TFTPPacket.ERROR, datagram.getAddress(), datagram.getPort());
    int index, length;
    byte[] data;
    StringBuffer buffer;

    data = datagram.getData();
    length = datagram.getLength();

    if (getType() != data[1])
        throw new TFTPPacketException("TFTP operator code does not match type.");

    _error = (((data[2] & 0xff) << 8) | (data[3] & 0xff));

    if (length < 5)
        throw new TFTPPacketException("Bad error packet. No message.");

    index = 4;
    buffer = new StringBuffer();

    while (index < length && data[index] != 0) {
        buffer.append((char) data[index]);
        ++index;
    }

    _message = buffer.toString();
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPDataPacket.java

/***
 * Creates a data packet based from a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>/*www  . j  a v  a2s .co m*/
 * @param datagram  The datagram containing the received data.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         data packet.
 ***/
TFTPDataPacket(DatagramPacket datagram) throws TFTPPacketException {
    super(TFTPPacket.DATA, datagram.getAddress(), datagram.getPort());

    _data = datagram.getData();
    _offset = 4;

    if (getType() != _data[1])
        throw new TFTPPacketException("TFTP operator code does not match type.");

    _blockNumber = (((_data[2] & 0xff) << 8) | (_data[3] & 0xff));

    _length = datagram.getLength() - 4;

    if (_length > MAX_DATA_LENGTH)
        _length = MAX_DATA_LENGTH;
}

From source file:ch.aschaefer.udp.DatagramSocketToControlMessageConverter.java

@Override
public ControlMessage convert(DatagramPacket source) {
    return new ControlMessage().timestamp(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.now()))
            .hex(toHex(source.getData())).source(source.getSocketAddress().toString())
            .targetHost(source.getAddress().getHostAddress()).targetPort(source.getPort());
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPRequestPacket.java

/***
 * Creates a request packet of a given type based on a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>//from   ww w.ja va2  s .  c  o m
 * @param type The type of the request (either TFTPPacket.READ_REQUEST or
 *             TFTPPacket.WRITE_REQUEST).
 * @param datagram  The datagram containing the received request.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         request packet of the appropriate type.
 ***/
TFTPRequestPacket(int type, DatagramPacket datagram) throws TFTPPacketException {
    super(type, datagram.getAddress(), datagram.getPort());

    byte[] data;
    int index, length;
    String mode;
    StringBuffer buffer;

    data = datagram.getData();

    if (getType() != data[1])
        throw new TFTPPacketException("TFTP operator code does not match type.");

    buffer = new StringBuffer();

    index = 2;
    length = datagram.getLength();

    while (index < length && data[index] != 0) {
        buffer.append((char) data[index]);
        ++index;
    }

    _filename = buffer.toString();

    if (index >= length)
        throw new TFTPPacketException("Bad filename and mode format.");

    buffer.setLength(0);
    ++index; // need to advance beyond the end of string marker
    while (index < length && data[index] != 0) {
        buffer.append((char) data[index]);
        ++index;
    }

    mode = buffer.toString().toLowerCase();
    length = _modeStrings.length;

    for (index = 0; index < length; index++) {
        if (mode.equals(_modeStrings[index])) {
            _mode = index;
            break;
        }
    }

    if (index >= length) {
        throw new TFTPPacketException("Unrecognized TFTP transfer mode: " + mode);
        // May just want to default to binary mode instead of throwing
        // exception.
        //_mode = TFTP.OCTET_MODE;
    }
}

From source file:com.springrts.springls.nat.NatHelpServer.java

/**
 * check UDP server for any new packets// ww  w  .  j  a v a 2 s  .  co  m
 */
private void checkForNewPackets() {

    DatagramPacket packet;
    while ((packet = fetchNextPackage()) != null) {
        InetAddress address = packet.getAddress();
        int clientPort = packet.getPort();
        String data = new String(packet.getData(), packet.getOffset(), packet.getLength());
        LOG.trace("*** UDP packet received from {} from port {}", address.getHostAddress(), clientPort);
        Client client = getContext().getClients().getClient(data);
        if (client == null) {
            continue;
        }
        client.setUdpSourcePort(clientPort);
        client.sendLine(String.format("UDPSOURCEPORT %d", clientPort));
    }
}

From source file:org.lwes.listener.DatagramDequeuer.java

protected void handleElement(DatagramQueueElement element) {
    if (element == null) {
        return;//from   w  w  w.  java 2 s.co m
    }

    DatagramPacket packet = element.getPacket();
    if (packet == null) {
        return;
    }

    /* get some metadata */
    long timestamp = element.getTimestamp();
    IPAddress address = new IPAddress(packet.getAddress());
    int port = packet.getPort();

    /* now try to deserialize the packet */
    try {
        /* don't validate the event for now to save time */
        Event event = factory.createEvent(packet.getData(), false);
        event.setInt64(Event.RECEIPT_TIME, timestamp);
        event.setIPAddress(Event.SENDER_IP, address);
        event.setUInt16(Event.SENDER_PORT, port);
        if (log.isTraceEnabled()) {
            log.trace("Dispatching event " + event.toString());
        }
        dispatchEvent(event);
    } catch (Exception e) {
        if (log.isWarnEnabled()) {
            log.warn("Unable to deserialize event in handleElement()", e);
        }
    }
}

From source file:org.vesalainen.nmea.processor.SNTPServer.java

@Override
public void run() {
    try {/* w ww  . j  a  va 2 s .  c o  m*/
        socket = new DatagramSocket(NTP_PORT);
        ntpMessage = new NtpV4Impl();
        DatagramPacket datagramPacket = ntpMessage.getDatagramPacket();

        while (true) {
            socket.receive(datagramPacket);
            log.info("NTP: received %s from %s %d", ntpMessage, datagramPacket.getAddress(),
                    datagramPacket.getPort());
            TimeStamp transmitTimeStamp = ntpMessage.getTransmitTimeStamp();
            ntpMessage.setLeapIndicator(LI_NO_WARNING);
            ntpMessage.setMode(MODE_SERVER);
            ntpMessage.setStratum(1);
            ntpMessage.setPrecision(-20);
            ntpMessage.setRootDelay(0);
            ntpMessage.setRootDispersion(0);
            ntpMessage.setReferenceId(ReferenceIdentifier.GPS);
            ntpMessage.setReferenceTime(TimeStamp.getNtpTime(clock.getZonedDateTime().toEpochSecond()));
            ntpMessage.setOriginateTimeStamp(transmitTimeStamp);
            long time = clock.millis();
            TimeStamp timeStamp = TimeStamp.getNtpTime(time);
            ntpMessage.setReceiveTimeStamp(timeStamp);
            ntpMessage.setTransmitTime(timeStamp);
            socket.send(datagramPacket);
            log.info("NTP: sent %s to %s %d diff=%d", ntpMessage, datagramPacket.getAddress(),
                    datagramPacket.getPort(), time - transmitTimeStamp.getTime());
        }
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex, "");
    }
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.cluster.impl.RelayClusterReceiverImpl.java

@Override
public void run() {
    byte[] receiveBuffer = new byte[UplinkReceiver.BUFFERSIZE];
    DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length);

    while (this.run.get()) {
        try {/*from   ww w.  j  av a 2 s.  c o  m*/
            this.sock.receive(packet);

            InetAddress ip = packet.getAddress();
            int port = packet.getPort();
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("received packet from RelayServer " + ip.getHostAddress() + ":" + port);
            }

            RelayServer me = this.relayServers.getMe();
            if (!(ip.equals(me.getIp()) && (port != this.relayClusterUdpPort))) {
                DatagramPacket msg = RelayClusterMessage.fromWireFormat(packet, this.reportOnce);
                if (msg != null) {
                    RelayServer rs = this.relayServers.getOrAdd(ip, port);
                    boolean packetCausedUpdate = this.packetHandler.processPacket(rs, msg);
                    if (this.relayClusterForwarding && packetCausedUpdate) {
                        if (this.logger.isDebugEnabled()) {
                            this.logger.debug(
                                    "forwarding packet from RelayServer " + ip.getHostAddress() + ":" + port);
                        }
                        this.relayClusterSender.addPacket(rs, msg);
                    }
                } else {
                    this.logger.error("Could not convert RelayClusterMessage from wire format");
                }
            } else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("skipping packet from RelayServer " + ip.getHostAddress() + ":" + port
                            + " since the packet came from me");
                }
            }
        } catch (Exception e) {
            if (!SocketException.class.equals(e.getClass())) {
                e.printStackTrace();
            }
        }
    }

    if (this.sock != null) {
        this.sock.close();
        this.sock = null;
    }
}