Java Code Examples for io.netty.channel.socket.DatagramPacket#sender()
The following examples show how to use
io.netty.channel.socket.DatagramPacket#sender() .
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 |
private static DnsResponse newResponse(DatagramPacket packet, ByteBuf buf) { final int id = buf.readUnsignedShort(); final int flags = buf.readUnsignedShort(); if (flags >> 15 == 0) { throw new CorruptedFrameException("not a response"); } final DnsResponse response = new DatagramDnsResponse( packet.sender(), packet.recipient(), id, DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)), DnsResponseCode.valueOf((byte) (flags & 0xf))); response.setRecursionDesired((flags >> 8 & 1) == 1); response.setAuthoritativeAnswer((flags >> 10 & 1) == 1); response.setTruncated((flags >> 9 & 1) == 1); response.setRecursionAvailable((flags >> 7 & 1) == 1); response.setZ(flags >> 4 & 0x7); return response; }
Example 2
Source File: DatagramDnsQueryDecoder.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
private static DnsQuery newQuery(DatagramPacket packet, ByteBuf buf) { final int id = buf.readUnsignedShort(); final int flags = buf.readUnsignedShort(); if (flags >> 15 == 1) { throw new CorruptedFrameException("not a query"); } final DnsQuery query = new DatagramDnsQuery( packet.sender(), packet.recipient(), id, DnsOpCode.valueOf((byte) (flags >> 11 & 0xf))); query.setRecursionDesired((flags >> 8 & 1) == 1); query.setZ(flags >> 4 & 0x7); return query; }
Example 3
Source File: PacketDecoder.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
@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 4
Source File: NetflowMessageAggregationHandler.java From graylog-plugin-netflow with Apache License 2.0 | 6 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { final SocketAddress remoteAddress = msg.sender(); final CodecAggregator.Result result; try (Timer.Context ignored = aggregationTimer.time()) { result = aggregator.addChunk(msg.content(), remoteAddress); } final ByteBuf completeMessage = result.getMessage(); if (completeMessage != null) { LOG.debug("Message aggregation completion, forwarding {}", completeMessage); ctx.fireChannelRead(completeMessage); } else if (result.isValid()) { LOG.debug("More chunks necessary to complete this message"); } else { invalidChunksMeter.mark(); LOG.debug("Message chunk was not valid and discarded."); } }
Example 5
Source File: SSLocalUdpProxyHandler.java From shadowsocks-java with MIT License | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext clientCtx, DatagramPacket msg) throws Exception { logger.debug("readableBytes:" + msg.content().readableBytes()); InetSocketAddress clientSender = msg.sender(); msg.content().skipBytes(3);//skip [5, 0, 0] SSAddrRequest addrRequest = SSAddrRequest.getAddrRequest(msg.content()); InetSocketAddress clientRecipient = new InetSocketAddress(addrRequest.host(), addrRequest.port()); proxy(clientSender, msg.content(), clientRecipient, clientCtx); }
Example 6
Source File: Udp2TcpHandler.java From AgentX with Apache License 2.0 | 5 votes |
@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 7
Source File: DiscoveryHandler.java From JRakNet with MIT License | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof DatagramPacket) { // Get packet and sender data DatagramPacket datagram = (DatagramPacket) msg; InetSocketAddress sender = datagram.sender(); RakNetPacket packet = new RakNetPacket(datagram); // If an exception happens it's because of this address this.causeAddress = sender; // Check if the address is blocked if (blocked.contains(sender.getAddress())) { datagram.release(); // No longer needed return; // Address blocked } // Handle the packet and release the buffer if (packet.getId() == RakNetPacket.ID_UNCONNECTED_PONG) { UnconnectedPong pong = new UnconnectedPong(packet); pong.decode(); if (!pong.failed()) { Discovery.updateDiscoveryData(sender, pong); logger.trace("Sent unconnected pong to discovery system"); } } Discovery.callEvent(listener -> { datagram.content().readerIndex(0); // Reset index listener.handleNettyMessage(sender, datagram.content()); }); if (datagram.release() /* No longer needed */) { logger.trace("Released datagram"); } else { logger.error("Memory leak: Failed to deallocate datagram when releasing it"); } // No exceptions occurred, release the suspect this.causeAddress = null; } }
Example 8
Source File: RakNetClientHandler.java From JRakNet with MIT License | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof DatagramPacket) { // Get packet and sender data DatagramPacket datagram = (DatagramPacket) msg; InetSocketAddress sender = datagram.sender(); RakNetPacket packet = new RakNetPacket(datagram); // If an exception happens it's because of this address this.causeAddress = sender; // Handle the packet and release the buffer client.handleMessage(sender, packet); logger.trace("Sent packet to client and reset datagram buffer read position"); client.callEvent(listener -> { datagram.content().readerIndex(0); // Reset position listener.handleNettyMessage(client, sender, datagram.content()); }); if (datagram.release() /* No longer needed */) { logger.trace("Released datagram"); } else { logger.error("Memory leak: Failed to deallocate datagram when releasing it"); } // No exceptions occurred, release the suspect this.causeAddress = null; } }
Example 9
Source File: RakNetServerHandler.java From JRakNet with MIT License | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof DatagramPacket) { // Get packet and sender data DatagramPacket datagram = (DatagramPacket) msg; InetSocketAddress sender = datagram.sender(); RakNetPacket packet = new RakNetPacket(datagram); // If an exception happens it's because of this address this.causeAddress = sender; // Check if address is blocked if (this.isAddressBlocked(sender.getAddress())) { BlockedAddress status = blocked.get(sender.getAddress()); if (!status.shouldUnblock()) { datagram.release(); // No longer needed return; // Address still blocked } this.unblockAddress(sender.getAddress()); } // Handle the packet and release the buffer server.handleMessage(sender, packet); logger.debug("Sent packet to server and reset datagram buffer read position"); server.callEvent(listener -> { datagram.content().readerIndex(0); // Reset index listener.handleNettyMessage(server, sender, datagram.content()); }); if (datagram.release() /* No longer needed */) { logger.trace("Released datagram"); } else { logger.error("Memory leak: Failed to deallocate datagram when releasing it"); } // No exceptions occurred, release the suspect this.causeAddress = null; } }
Example 10
Source File: KcpServer.java From jkcp with Apache License 2.0 | 5 votes |
/** * receive DatagramPacket * * @param dp */ private void onReceive(DatagramPacket dp) { if (this.running) { InetSocketAddress sender = dp.sender(); int hash = sender.hashCode(); hash = hash < 0 ? -hash : hash; this.workers[hash % workers.length].input(dp); } else { dp.release(); } }
Example 11
Source File: ReliableChannelHandler.java From riiablo with Apache License 2.0 | 5 votes |
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 12
Source File: ProtocolDecoder.java From plog with Apache License 2.0 | 5 votes |
private FourLetterCommand readCommand(DatagramPacket msg) { final ByteBuf content = msg.content(); final int trailLength = content.readableBytes() - 6; if (trailLength < 0) { return null; } final byte[] trail = new byte[trailLength]; final byte[] cmdBuff = new byte[4]; content.getBytes(2, cmdBuff, 0, 4); content.getBytes(6, trail, 0, trail.length); return new FourLetterCommand(new String(cmdBuff), msg.sender(), trail); }
Example 13
Source File: SipMessageDatagramDecoder.java From sipstack with MIT License | 5 votes |
/** * Framing an UDP packet is much simpler than for a stream based protocol * like TCP. We just assumes that everything is correct and therefore all is * needed is to read the first line, which is assumed to be a SIP initial * line, then read all headers as one big block and whatever is left better * be the payload (if there is one). * * Of course, things do go wrong. If e.g. the UDP packet is fragmented, then * we may end up with a partial SIP message but the user can either decide * to double check things by calling {@link SipMessage#verify()} or the user * will eventually notice when trying to access partial headers etc. * */ @Override protected void decode(final ChannelHandlerContext ctx, final DatagramPacket msg, final List<Object> out) throws Exception { final long arrivalTime = this.clock.getCurrentTimeMillis(); final ByteBuf content = msg.content(); // some clients are sending various types of pings even over // UDP, such as linphone which is sending "jaK\n\r". // According to RFC5626, the only valid ping over UDP // is to use a STUN request and since such a request is // at least 20 bytes we will simply ignore anything less // than that. And yes, there is no way that an actual // SIP message ever could be less than 20 bytes. if (content.readableBytes() < 20) { return; } final byte[] b = new byte[content.readableBytes()]; content.getBytes(0, b); final Buffer buffer = Buffers.wrap(b); SipParser.consumeSWS(buffer); final SipMessage sipMessage = SipParser.frame(buffer); // System.err.println("CSeq header: " + sipMessage.getCSeqHeader()); // final SipInitialLine initialLine = SipInitialLine.parse(buffer.readLine()); // final Buffer headers = buffer.readUntilDoubleCRLF(); // SipMessage sipMessage = null; // if (initialLine.isRequestLine()) { // sipMessage = new SipRequestImpl(initialLine.toRequestLine(), headers, buffer); // } else { // sipMessage = new SipResponseImpl(initialLine.toResponseLine(), headers, buffer); // } final Connection connection = new UdpConnection(ctx.channel(), msg.sender()); final SipMessageEvent event = new DefaultSipMessageEvent(connection, sipMessage, arrivalTime); out.add(event); }
Example 14
Source File: ConnectorServerEventHandler.java From Geyser with MIT License | 4 votes |
@Override public void onUnhandledDatagram(ChannelHandlerContext ctx, DatagramPacket packet) { new QueryPacketHandler(connector, packet.sender(), packet.content()); }
Example 15
Source File: KcpLoop.java From dfactor with MIT License | 4 votes |
@Override public void run() { this.onLoop = true; DatagramPacket pack = null; Kcp kcp = null; long tmStart = 0; long tmNow = 0; final long intervalDef = 10; long interval = 0; int recvCount = 0; int connId = 0; // while(this.onLoop){ try{ tmStart = System.currentTimeMillis(); //proc recv recvCount = 0; pack = queueRecv.poll(); while(pack != null){ connId = pack.content().readInt(); kcp = mapKcp.get(connId); if(kcp == null){ //new conn kcp = new Kcp(listener, kcpCfg, pack.sender(), connId, tmStart); mapKcp.put(connId, kcp); //notify listener.onChannelActive(kcp, connId); } kcp.onReceiveRaw(pack); // if(++recvCount < 1000){ pack = queueRecv.poll(); }else{ break; } } //proc update tmNow = System.currentTimeMillis(); final Iterator<Kcp> itKcp = mapKcp.values().iterator(); while(itKcp.hasNext()){ kcp = itKcp.next(); if(!kcp.isClosed()){ kcp.onUpdate(tmNow); }else{ itKcp.remove(); } } //wait interval = intervalDef - System.currentTimeMillis() + tmStart; if(interval > 5){ // pack = queueRecv.poll(interval, TimeUnit.MILLISECONDS); Thread.sleep(interval); } }catch(Throwable e){ e.printStackTrace(); } } // this.release(); }
Example 16
Source File: ReliableEndpoint.java From riiablo with Apache License 2.0 | 4 votes |
@Override public SocketAddress getRemoteAddress(ChannelHandlerContext ctx, DatagramPacket msg) { return msg.sender(); }