更新本地DNS服务器中的动态IP以获取主机名解析 [英] Updating Dynamic IP in local DNS server for hostname Resolution
问题描述
我正在使用设备dev1(主机名:dev1.example.com),设备2通过路由器连接在同一网络中,
I am using a devices dev1(hostname:dev1.example.com), dev2 connected in same network through router,
已与ISP建立连接.
When device dev1 got dynamic IP assigned, automatically device hostname and IP should be configured
在DNS服务器中,以便dev2可以使用主机名ping dev1.
in DNS server, so that dev2 can ping dev1 using hostname.
When i googled for the same, came across DDNS option. When i gone through it is asking to purchase domain and login with the domain credentials in router configuration.
I want to use my own domain without purchasing and enable DDNS support, is it possible to achieve this.
推荐答案
下面是将更新/etc/hosts文件中ip地址的脚本
below is the script which will update ip address in /etc/hosts file
#!/bin/sh
# Set the server's hostname
myHostName=$HOSTNAME
# Find and remove the current line with hostname at the end of line in /etc/hosts ($ is for end of line)
sed -i '/'$myHostName'$/ d' /etc/hosts
# Lookup the current IP Address and strip it out of the result
ipaddr=$(/usr/sbin/ip addr show eth0 | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1 -d'/')
# Add the server's current IP Address and HostName to /etc/hosts
echo "$ipaddr $myHostName" >>/etc/hosts
注意:在这种情况下,您必须将eth0更改为所需的端口名
Note: You must change eth0 to desired port name in your case
添加此脚本以在crontab中每分钟运行一次,因此,每当ip更改时,它将自动更新
add this script to run every minute in crontab, so whenever ip changes it will update automatically
# enter below command
crontab -e
# add below entry
* * * * * sh /root/update_dns_entry.sh
请注意,这只是一种解决方法,正确的做法是将您的mac地址设置为dhcp ip,以提供始终相同的ip,因为您是从ISP获取ip地址的,所以无法对其进行控制
Note this is just a workaround, right way doing this is setting up your mac address to dhcp ip to provide always same ip, since you are getting ip address from ISP, you do not have a control over it
这篇关于更新本地DNS服务器中的动态IP以获取主机名解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!