【ivp6服务器可通过ivp4网络访问教程】

服务器没有公网ivp4地址,只有ivp6地址,通过ddns可以实现ivp6访问到服务器,可是一般的网络没有配备ivp6,只有ivp4网络,这时可以使用Cloudflare的ivp6转ivp4实现访问,通过java定时调用Cloudflare接口更新ivp6地址值实现,前提是有域名

导入依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.6</version>
        </dependency>

需要填入url,秘钥,账号

package com.example.ddns;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.SocketException;
import java.util.*;

@Component
public class CloudFlareSetIp {
    private static final String TYPE = "AAAA";
    private static final String URL = ""; //这里填你的网址
    private static final String X_AUTH_KEY = "";//这里填你的秘钥
    private static final String X_AUTH_EMAIL = "";//这里填你的邮箱账号
    private static final String CONTENT_TYPE = "application/json";
    private static final int TTL = 1;
    private static final boolean PROXIED = true;

    @Autowired
    private Ipv6Util ipv6Util;

    /**
     * 定时任务
     */
    @Scheduled(cron = "0 0/15 * * * ?")
    public void setIp() throws IOException {
        String zoneUrl = "https://api.cloudflare.com/client/v4/zones?name=";
        zoneUrl += URL + "&status=active&page=1&per_page=20&order=status&direction=desc&match=all";
        String zoneId = null;
        String dnsId = null;
        String content = null;
        Map map = JSON.parseObject(sendGet(zoneUrl), Map.class);
        List<Map> result = (List) map.get("result");
        for (Map map1 : result) {
            zoneId = (String) map1.get("id");
        }
        String dnsUrl = "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/dns_records?";

        Map map1 = JSON.parseObject(sendGet(dnsUrl), Map.class);
        List<Map> result1 = (List) map1.get("result");
        for (Map map2 : result1) {
            dnsId = (String) map2.get("id");
            content = (String) map2.get("content");
        }
        String updateUrl = "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/dns_records/" + dnsId;

        if (ipv6Util.getIpv6().equals(content)) {
            System.out.println("dns地址未变动,不执行更新");
            return;
        }
        String s = doPut(updateUrl);
        System.out.println("接口返回信息:" + s);
        Map map2 = JSON.parseObject(s, Map.class);
        if (true == ((boolean) map2.get("success"))) {
            System.out.println("执行更新dns成功");
        } else {
            System.out.println("执行更新dns失败");
        }

    }

    public String sendGet(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-type", CONTENT_TYPE);
        httpGet.setHeader("DataEncoding", "UTF-8");
        httpGet.setHeader("X-Auth-Email", X_AUTH_EMAIL);
        httpGet.setHeader("X-Auth-Key", X_AUTH_KEY);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpGet.setConfig(requestConfig);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 原生字符串发送put请求
     *
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public String doPut(String url) throws SocketException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        httpPut.setHeader("Content-type", CONTENT_TYPE);
        httpPut.setHeader("DataEncoding", "UTF-8");
        httpPut.setHeader("X-Auth-Email", X_AUTH_EMAIL);
        httpPut.setHeader("X-Auth-Key", X_AUTH_KEY);

        //body
        JSONObject contentMap = new JSONObject();
        contentMap.put("type", TYPE);
        contentMap.put("name", URL);
        contentMap.put("content", ipv6Util.getIpv6());
        contentMap.put("ttl", TTL);
        contentMap.put("proxied", PROXIED);

        CloseableHttpResponse httpResponse = null;
        try {
            httpPut.setEntity(new StringEntity(contentMap.toJSONString()));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}

获取网卡ipv6地址,需要先查看服务器网卡名称填入即可

package com.example.ddns;

import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

@Component
public class Ipv6Util {
    /**
     * 获取ipv6地址信息
     *
     * @return
     * @throws SocketException
     */
    public String getIpv6() throws SocketException {
        try {
            InetAddress ads = null;
            Enumeration<?> adds = NetworkInterface.getNetworkInterfaces();
            String myIp = null;
            while (adds.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) adds.nextElement();
                Enumeration<?> inetAds = netInterface.getInetAddresses();

                while (inetAds.hasMoreElements()) {
                    ads = (InetAddress) inetAds.nextElement();
                    //判断是否与InetAddress相同且非保留地址
                    if (ads instanceof InetAddress && !isReservedAddr(ads)) {
                        //ip地址
                        String ipAddress = ads.getHostAddress();
                        //对应ip的网卡名称
                        String eth = netInterface.getName();
                        //System.out.println(eth + "-" + ipAddress);
                        //网卡信息过滤
                        //enp2s0是我的网卡名称,需要填入自己的网卡名称
                        if ("enp2s0".equals(eth) && ipAddress.length() > 20) {
                            myIp = ipAddress.replace("%enp2s0", "");
                        }
                    }
                }
            }
            System.out.println("ipv6地址是:" + myIp);
            return myIp;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("获取ipv6地址失败-" + e);
            return null;
        }
    }

    private boolean isReservedAddr(InetAddress inetAddr) {
        if (inetAddr.isAnyLocalAddress() || inetAddr.isLinkLocalAddress() || inetAddr.isLoopbackAddress()) {
            return true;
        }
        return false;
    }
}

打包后在linux后台运行jar包即可

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啥也不会lll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值