AddressUtils.java 文件源码

java
阅读 29 收藏 0 点赞 0 评论 0

项目:bt 作者:
public static InetAddress getDefaultRoute(Class<? extends InetAddress> type) {
    InetAddress target = null;

    ProtocolFamily family = type == Inet6Address.class ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;

    try(DatagramChannel chan=DatagramChannel.open(family)) {
        if(type == Inet4Address.class)
            target = InetAddress.getByAddress(new byte[] {8,8,8,8});
        if(type == Inet6Address.class)
            target = InetAddress.getByName("2001:4860:4860::8888");

        chan.connect(new InetSocketAddress(target,63));

        InetSocketAddress soa = (InetSocketAddress) chan.getLocalAddress();
        InetAddress local = soa.getAddress();

        if(type.isInstance(local) && !local.isAnyLocalAddress())
            return local;
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号