Search in sources :

Example 66 with DatagramPacket

use of java.net.DatagramPacket in project openhab1-addons by openhab.

the class MaxCubeDiscover method discoverIp.

/**
     * Automatic UDP discovery of a MAX!Cube
     * 
     * @return if the cube is found, returns the IP address as a string. Otherwise returns null
     */
public static final String discoverIp() {
    String maxCubeIP = null;
    String maxCubeName = null;
    String rfAddress = null;
    Logger logger = LoggerFactory.getLogger(MaxCubeDiscover.class);
    DatagramSocket bcReceipt = null;
    DatagramSocket bcSend = null;
    // Find the MaxCube using UDP broadcast
    try {
        bcSend = new DatagramSocket();
        bcSend.setBroadcast(true);
        byte[] sendData = "eQ3Max*\0**********I".getBytes();
        // Broadcast the message over all the network interfaces
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress[] broadcast = new InetAddress[2];
                broadcast[0] = InetAddress.getByName("224.0.0.1");
                broadcast[1] = interfaceAddress.getBroadcast();
                for (InetAddress bc : broadcast) {
                    // Send the broadcast package!
                    if (bc != null) {
                        try {
                            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, 23272);
                            bcSend.send(sendPacket);
                        } catch (IOException e) {
                            logger.debug("IO error during MAX! Cube discovery: {}", e.getMessage());
                        } catch (Exception e) {
                            logger.debug(e.getMessage());
                            logger.debug(Utils.getStackTrace(e));
                        }
                        logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName());
                    }
                }
            }
        }
        logger.trace("Done looping over all network interfaces. Now waiting for a reply!");
        bcSend.close();
        bcReceipt = new DatagramSocket(23272);
        bcReceipt.setReuseAddress(true);
        // Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        bcReceipt.receive(receivePacket);
        // We have a response
        logger.trace("Broadcast response from server: {}", receivePacket.getAddress());
        // Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.startsWith("eQ3Max")) {
            maxCubeIP = receivePacket.getAddress().getHostAddress();
            maxCubeName = message.substring(0, 8);
            rfAddress = message.substring(8, 18);
            logger.debug("Found at: {}", maxCubeIP);
            logger.debug("Name    : {}", maxCubeName);
            logger.debug("Serial  : {}", rfAddress);
            logger.trace("Message : {}", message);
        } else {
            logger.info("No Max!Cube gateway found on network");
        }
    } catch (IOException e) {
        logger.debug("IO error during MAX! Cube discovery: {}", e.getMessage());
    } catch (Exception e) {
        logger.debug(e.getMessage());
        logger.debug(Utils.getStackTrace(e));
    } finally {
        try {
            if (bcReceipt != null) {
                bcReceipt.close();
            }
        } catch (Exception e) {
            logger.debug(e.toString());
        }
        try {
            if (bcSend != null) {
                bcSend.close();
            }
        } catch (Exception e) {
            logger.debug(e.toString());
        }
    }
    return maxCubeIP;
}
Also used : DatagramSocket(java.net.DatagramSocket) InterfaceAddress(java.net.InterfaceAddress) DatagramPacket(java.net.DatagramPacket) NetworkInterface(java.net.NetworkInterface) IOException(java.io.IOException) Logger(org.slf4j.Logger) InetAddress(java.net.InetAddress) IOException(java.io.IOException)

Example 67 with DatagramPacket

use of java.net.DatagramPacket in project pinpoint by naver.

the class DatagramPacketFactoryTest method testCreate.

@Test
public void testCreate() throws Exception {
    int bufferLength = 10;
    DatagramPacketFactory factory = new DatagramPacketFactory(bufferLength);
    DatagramPacket packet = factory.create();
    Assert.assertEquals(bufferLength, packet.getLength());
}
Also used : DatagramPacket(java.net.DatagramPacket) Test(org.junit.Test)

Example 68 with DatagramPacket

use of java.net.DatagramPacket in project pinpoint by naver.

the class DatagramPacketFactoryTest method testBeforeReturn.

@Test
public void testBeforeReturn() throws Exception {
    int bufferLength = 10;
    DatagramPacketFactory factory = new DatagramPacketFactory(bufferLength);
    DatagramPacket packet = factory.create();
    packet.setLength(1);
    factory.beforeReturn(packet);
    Assert.assertEquals(bufferLength, packet.getLength());
}
Also used : DatagramPacket(java.net.DatagramPacket) Test(org.junit.Test)

Example 69 with DatagramPacket

use of java.net.DatagramPacket in project pinpoint by naver.

the class DefaultObjectPoolTest method testReset.

@Test
public void testReset() throws Exception {
    DefaultObjectPool<DatagramPacket> pool = new DefaultObjectPool<>(new DatagramPacketFactory(), 1);
    PooledObject<DatagramPacket> pooledObject = pool.getObject();
    DatagramPacket packet = pooledObject.getObject();
    packet.setLength(10);
    pooledObject.returnObject();
    DatagramPacket check = pooledObject.getObject();
    Assert.assertSame(check, packet);
    Assert.assertEquals(packet.getLength(), DatagramPacketFactory.UDP_MAX_PACKET_LENGTH);
}
Also used : DatagramPacket(java.net.DatagramPacket) Test(org.junit.Test)

Example 70 with DatagramPacket

use of java.net.DatagramPacket in project XobotOS by xamarin.

the class UDPMessageChannel method processIncomingDataPacket.

/**
     * Process an incoming datagram
     *
     * @param packet
     *            is the incoming datagram packet.
     */
private void processIncomingDataPacket(DatagramPacket packet) throws Exception {
    this.peerAddress = packet.getAddress();
    int packetLength = packet.getLength();
    // Read bytes and put it in a eueue.
    byte[] bytes = packet.getData();
    byte[] msgBytes = new byte[packetLength];
    System.arraycopy(bytes, 0, msgBytes, 0, packetLength);
    // Do debug logging.
    if (sipStack.isLoggingEnabled()) {
        this.sipStack.getStackLogger().logDebug("UDPMessageChannel: processIncomingDataPacket : peerAddress = " + peerAddress.getHostAddress() + "/" + packet.getPort() + " Length = " + packetLength);
    }
    SIPMessage sipMessage = null;
    try {
        this.receptionTime = System.currentTimeMillis();
        sipMessage = myParser.parseSIPMessage(msgBytes);
        myParser = null;
    } catch (ParseException ex) {
        // let go of the parser reference.
        myParser = null;
        if (sipStack.isLoggingEnabled()) {
            this.sipStack.getStackLogger().logDebug("Rejecting message !  " + new String(msgBytes));
            this.sipStack.getStackLogger().logDebug("error message " + ex.getMessage());
            this.sipStack.getStackLogger().logException(ex);
        }
        // JvB: send a 400 response for requests (except ACK)
        // Currently only UDP, @todo also other transports
        String msgString = new String(msgBytes, 0, packetLength);
        if (!msgString.startsWith("SIP/") && !msgString.startsWith("ACK ")) {
            String badReqRes = createBadReqRes(msgString, ex);
            if (badReqRes != null) {
                if (sipStack.isLoggingEnabled()) {
                    sipStack.getStackLogger().logDebug("Sending automatic 400 Bad Request:");
                    sipStack.getStackLogger().logDebug(badReqRes);
                }
                try {
                    this.sendMessage(badReqRes.getBytes(), peerAddress, packet.getPort(), "UDP", false);
                } catch (IOException e) {
                    this.sipStack.getStackLogger().logException(e);
                }
            } else {
                if (sipStack.isLoggingEnabled()) {
                    sipStack.getStackLogger().logDebug("Could not formulate automatic 400 Bad Request");
                }
            }
        }
        return;
    }
    if (sipMessage == null) {
        if (sipStack.isLoggingEnabled()) {
            this.sipStack.getStackLogger().logDebug("Rejecting message !  + Null message parsed.");
        }
        if (pingBackRecord.get(packet.getAddress().getHostAddress() + ":" + packet.getPort()) == null) {
            byte[] retval = "\r\n\r\n".getBytes();
            DatagramPacket keepalive = new DatagramPacket(retval, 0, retval.length, packet.getAddress(), packet.getPort());
            ((UDPMessageProcessor) this.messageProcessor).sock.send(keepalive);
            this.sipStack.getTimer().schedule(new PingBackTimerTask(packet.getAddress().getHostAddress(), packet.getPort()), 1000);
        }
        return;
    }
    ViaList viaList = sipMessage.getViaHeaders();
    // Check for the required headers.
    if (sipMessage.getFrom() == null || sipMessage.getTo() == null || sipMessage.getCallId() == null || sipMessage.getCSeq() == null || sipMessage.getViaHeaders() == null) {
        String badmsg = new String(msgBytes);
        if (sipStack.isLoggingEnabled()) {
            this.sipStack.getStackLogger().logError("bad message " + badmsg);
            this.sipStack.getStackLogger().logError(">>> Dropped Bad Msg " + "From = " + sipMessage.getFrom() + "To = " + sipMessage.getTo() + "CallId = " + sipMessage.getCallId() + "CSeq = " + sipMessage.getCSeq() + "Via = " + sipMessage.getViaHeaders());
        }
        return;
    }
    // For response, just get the port from the packet.
    if (sipMessage instanceof SIPRequest) {
        Via v = (Via) viaList.getFirst();
        Hop hop = sipStack.addressResolver.resolveAddress(v.getHop());
        this.peerPort = hop.getPort();
        this.peerProtocol = v.getTransport();
        this.peerPacketSourceAddress = packet.getAddress();
        this.peerPacketSourcePort = packet.getPort();
        try {
            this.peerAddress = packet.getAddress();
            // Check to see if the received parameter matches
            // the peer address and tag it appropriately.
            boolean hasRPort = v.hasParameter(Via.RPORT);
            if (hasRPort || !hop.getHost().equals(this.peerAddress.getHostAddress())) {
                v.setParameter(Via.RECEIVED, this.peerAddress.getHostAddress());
            }
            if (hasRPort) {
                v.setParameter(Via.RPORT, Integer.toString(this.peerPacketSourcePort));
            }
        } catch (java.text.ParseException ex1) {
            InternalErrorHandler.handleException(ex1);
        }
    } else {
        this.peerPacketSourceAddress = packet.getAddress();
        this.peerPacketSourcePort = packet.getPort();
        this.peerAddress = packet.getAddress();
        this.peerPort = packet.getPort();
        this.peerProtocol = ((Via) viaList.getFirst()).getTransport();
    }
    this.processMessage(sipMessage);
}
Also used : Hop(javax.sip.address.Hop) IOException(java.io.IOException) SIPRequest(gov.nist.javax.sip.message.SIPRequest) Via(gov.nist.javax.sip.header.Via) ViaList(gov.nist.javax.sip.header.ViaList) DatagramPacket(java.net.DatagramPacket) SIPMessage(gov.nist.javax.sip.message.SIPMessage) ParseException(java.text.ParseException) ParseException(java.text.ParseException)

Aggregations

DatagramPacket (java.net.DatagramPacket)334 DatagramSocket (java.net.DatagramSocket)138 IOException (java.io.IOException)137 InetAddress (java.net.InetAddress)77 SocketException (java.net.SocketException)48 Test (org.junit.Test)37 InetSocketAddress (java.net.InetSocketAddress)34 SocketTimeoutException (java.net.SocketTimeoutException)30 UnknownHostException (java.net.UnknownHostException)26 MulticastSocket (java.net.MulticastSocket)19 InterruptedIOException (java.io.InterruptedIOException)17 SocketAddress (java.net.SocketAddress)16 ByteBuffer (java.nio.ByteBuffer)11 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 SyslogConnection (org.opennms.netmgt.syslogd.api.SyslogConnection)11 ArrayList (java.util.ArrayList)10 PortUnreachableException (java.net.PortUnreachableException)9 SyslogMessageLogDTO (org.opennms.netmgt.syslogd.api.SyslogMessageLogDTO)8 BindException (java.net.BindException)7 Transactional (org.springframework.transaction.annotation.Transactional)7