Java Code Examples for io.netty.channel.socket.DatagramPacket#content()

The following examples show how to use io.netty.channel.socket.DatagramPacket#content() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatagramDnsResponseDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {
    final ByteBuf buf = packet.content();

    final DnsResponse response = newResponse(packet, buf);
    boolean success = false;
    try {
        final int questionCount = buf.readUnsignedShort();
        final int answerCount = buf.readUnsignedShort();
        final int authorityRecordCount = buf.readUnsignedShort();
        final int additionalRecordCount = buf.readUnsignedShort();

        decodeQuestions(response, buf, questionCount);
        decodeRecords(response, DnsSection.ANSWER, buf, answerCount);
        decodeRecords(response, DnsSection.AUTHORITY, buf, authorityRecordCount);
        decodeRecords(response, DnsSection.ADDITIONAL, buf, additionalRecordCount);

        out.add(response);
        success = true;
    } finally {
        if (!success) {
            response.release();
        }
    }
}
 
Example 2
Source File: DatagramDnsQueryDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {
    final ByteBuf buf = packet.content();

    final DnsQuery query = newQuery(packet, buf);
    boolean success = false;
    try {
        final int questionCount = buf.readUnsignedShort();
        final int answerCount = buf.readUnsignedShort();
        final int authorityRecordCount = buf.readUnsignedShort();
        final int additionalRecordCount = buf.readUnsignedShort();

        decodeQuestions(query, buf, questionCount);
        decodeRecords(query, DnsSection.ANSWER, buf, answerCount);
        decodeRecords(query, DnsSection.AUTHORITY, buf, authorityRecordCount);
        decodeRecords(query, DnsSection.ADDITIONAL, buf, additionalRecordCount);

        out.add(query);
        success = true;
    } finally {
        if (!success) {
            query.release();
        }
    }
}
 
Example 3
Source File: KcpTestClient.java    From dfactor with MIT License 6 votes vote down vote up
@Override
		protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket pack) throws Exception {
			final ByteBuf buf = pack.content();
			final int size = buf.readableBytes();
			if(size > 0){
				int connId = 0;
				if(buf.readByte()==Kcp.FLAG && size > 1 + 4){ //valid kcp head
					connId = buf.getInt(buf.readerIndex());
				}
				if(connId > 0){ //valid kcp pack
					pack.retain();
					queueRecv.offer(pack);
//					log.I("Recv kcp pack, sender="+pack.sender().toString());
				}else{  //normal udp pack
					log.I("Recv udp pack, sender="+pack.sender().toString());
				}
			}else{
				log.E("Invalid pack, len=0, sender="+pack.sender().toString());
			}
		}
 
Example 4
Source File: Crc32Decode.java    From java-Kcp with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof DatagramPacket) {
        DatagramPacket datagramPacket = (DatagramPacket) msg;
        ByteBuf data = datagramPacket.content();
        long checksum =  data.readUnsignedIntLE();
        ByteBuffer byteBuffer = data.nioBuffer(data.readerIndex(),data.readableBytes());
        crc32.reset();
        crc32.update(byteBuffer);
        if(checksum!=crc32.getValue()){
            Snmp.snmp.getInCsumErrors().increment();
            return;
        }
    }
   ctx.fireChannelRead(msg);
}
 
Example 5
Source File: PacketDecoder.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out)
        throws Exception {
    ByteBuf buf = packet.content();
    int length = buf.readableBytes();
    if (length <= 1 || length >= MAXSIZE) {
        logger
                .error("UDP rcv bad packet, from {} length = {}", ctx.channel().remoteAddress(), length);
        return;
    }
    byte[] encoded = new byte[length];
    buf.readBytes(encoded);
    try {
        UdpEvent event = new UdpEvent(Message.parse(encoded), packet.sender());
        out.add(event);
    } catch (Exception e) {
        logger.error("Parse msg failed, type {}, len {}, address {}", encoded[0], encoded.length,
                packet.sender());
    }
}
 
Example 6
Source File: IrisUpnpServer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(@Nullable ChannelHandlerContext ctx, @Nullable Object msg) throws Exception {
   DatagramPacket packet = (DatagramPacket)msg;
   if (packet == null) {
      return;
   }

   try {
      ByteBuf content = packet.content();
      if (log.isTraceEnabled()) {
         log.trace("recv upnp message: {}", content.toString(StandardCharsets.UTF_8));
      }

      if (content.readableBytes() > 5 &&
          content.getByte(content.readerIndex()) == 'H' &&
          content.getByte(content.readerIndex()+1) == 'T' &&
          content.getByte(content.readerIndex()+2) == 'T' &&
          content.getByte(content.readerIndex()+3) == 'P' &&
          content.getByte(content.readerIndex()+4) == '/') {
         handleResponse(ctx, packet);
      } else {
         handleRequest(ctx, packet);
      }
   } catch (Throwable th) {
      log.debug("error processing upnp packet:", th);
   } finally {
      if (packet.refCnt() > 0) {
         packet.release(packet.refCnt());
      }
   }
}
 
Example 7
Source File: PacketDecoder.java    From mpush with Apache License 2.0 5 votes vote down vote up
public static Packet decodeFrame(DatagramPacket frame) {
    ByteBuf in = frame.content();
    int readableBytes = in.readableBytes();
    int bodyLength = in.readInt();
    if (readableBytes < (bodyLength + Packet.HEADER_LEN)) {
        return null;
    }

    return decodePacket(new UDPPacket(in.readByte()
            , frame.sender()), in, bodyLength);
}
 
Example 8
Source File: UdpProtostuffDecoder.java    From c5-replicator with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket dgram, List<Object> out) throws Exception {
  ByteBuf msg = dgram.content();

  ByteBufferInput input = new ByteBufferInput(msg.nioBuffer(), protostuffEncoded);
  T newMsg = schema.newMessage();
  schema.mergeFrom(input, newMsg);
  out.add(newMsg);
}
 
Example 9
Source File: SourceLogListenHandler.java    From async-gamequery-lib with MIT License 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    ByteBuf data = msg.content();
    if (data.readableBytes() > 6 && data.readIntLE() == -1) {
        byte[] raw = new byte[data.readableBytes() - 2];
        data.readBytes(raw);
        data.skipBytes(2);
        //Pass to the callback
        if (logEventCallback != null)
            logEventCallback.accept(new SourceLogEntry(new String(raw, Charsets.UTF_8), msg.sender()));
    }
}
 
Example 10
Source File: Udp2TcpHandler.java    From AgentX with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    DatagramPacket datagram = (DatagramPacket) msg;
    InetSocketAddress sender = datagram.sender();
    Channel tcpChannel = XChannelMapper.getTcpChannel(sender);
    if (tcpChannel == null) {
        // udpSource not registered, actively discard this packet
        // without register, an udp channel cannot relate to any tcp channel, so remove the map
        XChannelMapper.removeUdpMapping(sender);
        log.warn("Bad Connection! (unexpected udp datagram from {})", sender);
    } else if (tcpChannel.isActive()) {
        ByteBuf byteBuf = datagram.content();
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                log.info("\t          Proxy << Target \tFrom   {}:{}", sender.getHostString(), sender.getPort());

                // write udp payload via tcp channel
                tcpChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(requestResolver.wrap(XRequest.Channel.UDP, bytes))));
                log.info("\tClient << Proxy           \tGet [{} bytes]", bytes.length);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 11
Source File: DatagramPacketToByteBuf.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out)
    throws Exception {
    final ByteBuf buf = packet.content();
    buf.retain();
    out.add(buf);
}
 
Example 12
Source File: ReliableChannelHandler.java    From riiablo with Apache License 2.0 5 votes vote down vote up
protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
  InetSocketAddress sender = packet.sender();
  Gdx.app.log(TAG, "messageReceived received packet from " + sender.getHostName() + ":" + sender.getPort());
  ByteBuf in = packet.content();
  if (DEBUG_INBOUND) Gdx.app.debug(TAG, "  " + ByteBufUtil.hexDump(in));
  endpoint.messageReceived(ctx, packet.sender(), packet);
}
 
Example 13
Source File: LispMessageDecoder.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg,
                      List<Object> list) throws Exception {
    ByteBuf byteBuf = msg.content();
    LispMessageReader reader = LispMessageReaderFactory.getReader(byteBuf);
    LispMessage message = (LispMessage) reader.readFrom(byteBuf);
    message.configSender(msg.sender());
    list.add(message);
}
 
Example 14
Source File: ProtocolDecoder.java    From plog with Apache License 2.0 4 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out)
        throws Exception {
    final ByteBuf content = msg.content();
    final byte versionIdentifier = content.getByte(0);
    // versions are non-printable characters, push down the pipeline send as-is.
    if (versionIdentifier < 0 || versionIdentifier > 31) {
        log.debug("Unboxed UDP message");
        stats.receivedUdpSimpleMessage();
        msg.retain();
        out.add(new MessageImpl(content, null));
    } else if (versionIdentifier == 0) {
        final byte typeIdentifier = content.getByte(1);
        switch (typeIdentifier) {
            case 0:
                final FourLetterCommand cmd = readCommand(msg);
                if (cmd != null) {
                    log.debug("v0 command");
                    out.add(cmd);
                } else {
                    stats.receivedUnknownCommand();
                }
                break;
            case 1:
                log.debug("v0 multipart message: {}", msg);
                try {
                    final Fragment fragment = Fragment.fromDatagram(msg);
                    stats.receivedV0MultipartFragment(fragment.getFragmentIndex());
                    msg.retain();
                    out.add(fragment);
                } catch (IllegalArgumentException e) {
                    log.error("Invalid header", e);
                    stats.receivedV0InvalidMultipartHeader();
                }
                break;
            default:
                stats.receivedV0InvalidType();
        }
    } else {
        stats.receivedUdpInvalidVersion();
    }
}
 
Example 15
Source File: SessionManager.java    From Nukkit with GNU General Public License v3.0 4 votes vote down vote up
private boolean receivePacket() throws Exception {
    DatagramPacket datagramPacket = this.socket.readPacket();
    if (datagramPacket != null) {
        // Check this early
        try {
            String source = datagramPacket.sender().getHostString();
            currentSource = source; //in order to block address
            if (this.block.containsKey(source)) {
                return true;
            }

            if (this.ipSec.containsKey(source)) {
                this.ipSec.put(source, this.ipSec.get(source) + 1);
            } else {
                this.ipSec.put(source, 1);
            }

            ByteBuf byteBuf = datagramPacket.content();
            if (byteBuf.readableBytes() == 0) {
                // Exit early to process another packet
                return true;
            }
            byte[] buffer = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(buffer);
            int len = buffer.length;
            int port = datagramPacket.sender().getPort();

            this.receiveBytes += len;

            byte pid = buffer[0];

            if (pid == UNCONNECTED_PONG.ID) {
                return false;
            }

            Packet packet = this.getPacketFromPool(pid);
            if (packet != null) {
                packet.buffer = buffer;
                this.getSession(source, port).handlePacket(packet);
                return true;
            } else if (pid == UNCONNECTED_PING.ID) {
                packet = new UNCONNECTED_PING();
                packet.buffer = buffer;
                packet.decode();

                UNCONNECTED_PONG pk = new UNCONNECTED_PONG();
                pk.serverID = this.getID();
                pk.pingID = ((UNCONNECTED_PING) packet).pingID;
                pk.serverName = this.getName();
                this.sendPacket(pk, source, port);
            } else if (buffer.length != 0) {
                this.streamRAW(source, port, buffer);
                return true;
            } else {
                return false;
            }
        } finally {
            datagramPacket.release();
        }
    }

    return false;
}
 
Example 16
Source File: UdpPacketToByteBuf.java    From timely with Apache License 2.0 4 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    ByteBuf buf = msg.content();
    buf.retain();
    out.add(buf);
}
 
Example 17
Source File: SessionManager.java    From Jupiter with GNU General Public License v3.0 4 votes vote down vote up
private boolean receivePacket() throws Exception {
    DatagramPacket datagramPacket = this.socket.readPacket();
    if (datagramPacket != null) {
        // Check this early
        try {
            String source = datagramPacket.sender().getHostString();
            currentSource = source; //in order to block address
            if (this.block.containsKey(source)) {
                return true;
            }

            if (this.ipSec.containsKey(source)) {
                this.ipSec.put(source, this.ipSec.get(source) + 1);
            } else {
                this.ipSec.put(source, 1);
            }

            ByteBuf byteBuf = datagramPacket.content();
            if (byteBuf.readableBytes() == 0) {
                // Exit early to process another packet
                return true;
            }
            byte[] buffer = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(buffer);
            int len = buffer.length;
            int port = datagramPacket.sender().getPort();

            this.receiveBytes += len;

            byte pid = buffer[0];

            if (pid == UNCONNECTED_PONG.ID) {
                return false;
            }

            Packet packet = this.getPacketFromPool(pid);
            if (packet != null) {
                packet.buffer = buffer;
                this.getSession(source, port).handlePacket(packet);
                return true;
            } else if (pid == UNCONNECTED_PING.ID) {
                packet = new UNCONNECTED_PING();
                packet.buffer = buffer;
                packet.decode();

                UNCONNECTED_PONG pk = new UNCONNECTED_PONG();
                pk.serverID = this.getID();
                pk.pingID = ((UNCONNECTED_PING) packet).pingID;
                pk.serverName = this.getName();
                this.sendPacket(pk, source, port);
            } else if (buffer.length != 0) {
                this.streamRAW(source, port, buffer);
                return true;
            } else {
                return false;
            }
        } finally {
            datagramPacket.release();
        }
    }

    return false;
}
 
Example 18
Source File: SessionManager.java    From Nemisys with GNU General Public License v3.0 4 votes vote down vote up
private boolean receivePacket() throws Exception {
    DatagramPacket datagramPacket = this.socket.readPacket();
    if (datagramPacket != null) {
        ByteBuf byteBuf = datagramPacket.content();
        byte[] buffer = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(buffer);
        byteBuf.release();
        int len = buffer.length;
        String source = datagramPacket.sender().getHostString();
        currentSource = source; //in order to block address
        int port = datagramPacket.sender().getPort();
        if (len > 0) {
            this.receiveBytes += len;
            if (this.block.containsKey(source)) {
                return true;
            }

            if (this.ipSec.containsKey(source)) {
                this.ipSec.put(source, this.ipSec.get(source) + 1);
            } else {
                this.ipSec.put(source, 1);
            }

            byte pid = buffer[0];

            if (pid == UNCONNECTED_PONG.ID) {
                return false;
            }

            Packet packet = this.getPacketFromPool(pid);
            if (packet != null) {
                packet.buffer = buffer;
                this.getSession(source, port).handlePacket(packet);
                return true;
            } else if (pid == UNCONNECTED_PING.ID) {
                packet = new UNCONNECTED_PING();
                packet.buffer = buffer;
                packet.decode();

                UNCONNECTED_PONG pk = new UNCONNECTED_PONG();
                pk.serverID = this.getID();
                pk.pingID = ((UNCONNECTED_PING) packet).pingID;
                pk.serverName = this.getName();
                this.sendPacket(pk, source, port);
            } else if (buffer.length != 0) {
                this.streamRAW(source, port, buffer);
                return true;
            } else {
                return false;
            }
        }
    }

    return false;
}
 
Example 19
Source File: ConnectorServerEventHandler.java    From Geyser with MIT License 4 votes vote down vote up
@Override
public void onUnhandledDatagram(ChannelHandlerContext ctx, DatagramPacket packet) {
    new QueryPacketHandler(connector, packet.sender(), packet.content());
}
 
Example 20
Source File: Packet.java    From JRakNet with MIT License 2 votes vote down vote up
/**
 * Creates packet from an existing {@link DatagramPacket}.
 * 
 * @param datagram
 *            the {@link DatagramPacket} to read from.
 */
public Packet(DatagramPacket datagram) {
	this(datagram.content());
}