【问题标题】:Obtaining Source IP address of Datagram packet UDP Netty 4.1获取数据报包UDP Netty 4.1的源IP地址
【发布时间】:2017-05-13 04:59:36
【问题描述】:

我已经使用 netty 4.1 设置了一个基本的 UDP 服务器,它可以很好地从数据包中读取数据。我想向服务器添加一个功能,以便在收到 UDP 数据包后回复客户端。这样做的最佳方法是什么。我知道UDP是一种无连接的通信方式,但是你应该可以获取IP地址并回复客户端吧?

我的代码如下;

public final class Server {

private static final int PORT = Integer.parseInt(System.getProperty("port", "6565"));

public static void runCommand () throws Exception {
    System.out.print("Server is started on port = "+PORT+"\n");
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .handler(new ServerHandler());

        b.bind(PORT).sync().channel().closeFuture().await();
    } finally {
        group.shutdownGracefully();
    }
}

}

public class ServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

@Override
public void channelRead0 (ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    System.err.println ("Messaged received on " + new Date() + ":\r");
    System.err.println(packet.content().toString(CharsetUtil.UTF_8) + "\r\n");
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
    ctx.flush();
}


@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
}

}

有人可以为我指出如何获取源IP地址的正确方向吗?非常感谢您的帮助

【问题讨论】:

    标签: java udp netty datagram


    【解决方案1】:

    用途:

    packet.sender().getAddress()
    

    【讨论】:

      【解决方案2】:

      源IP地址在DatagramPacket中。

      【讨论】:

      • 使用上面的代码,我只是解码数据报消息。由于在 netty 文档中看不到选项,如何解码数据报头?
      • 奇怪的地方。它不在 Netty 文档中。它在java.net.DatagramPacket 文档中。
      猜你喜欢
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多