-2

I wanted to get the IP of my DHCP server into a bash variable.

like : IP="192.168.1.254"

I know this IP can be found in /var/lib/dhcp/dhclient.leases or in /var/log/syslog but I don't know of to extract it and put it in variable during my script (bash)

EDIT: file dhclient.leases look's like

lease {
  interface "eth0";
  fixed-address 192.168.1.200;
  option subnet-mask 255.255.255.0;
  option routers 192.168.1.254;
  option dhcp-lease-time 7200;
  option dhcp-message-type 5;
  option domain-name-servers 192.168.1.254;
  option dhcp-server-identifier 192.168.1.254;
  option host-name "bertin-Latitude-E6430s";
  option domain-name "laboelec";
  renew 1 2015/02/16 10:54:34;
  rebind 1 2015/02/16 11:53:49;
  expire 1 2015/02/16 12:08:49;
}

I want the IP from line option dhcp-server-identifier 192.168.1.254;.

Jérémy
  • 1,790
  • 1
  • 24
  • 40
  • 2
    post the content of those file which you want to extract, only one or two lines after and before the main line will do. – Jahid Jun 18 '15 at 13:52
  • 1
    You didn't say what OS you're using and on my Linux Mint 17.1 the `/var/lib/dhcp/dhclient.leases` file is empty even though my network adapter is using DHCP and what are you going to do if/when the `/var/log/syslog` file has rolled over and doesn't yet contain any networking information. – user3439894 Jun 18 '15 at 14:01
  • 1
    Is the string `option dhcp-server-identifier` unique in the file? – Jahid Jun 18 '15 at 14:04
  • I didn't know that `/var/lib/dhcp/dhclient.leases` could be empty ! – Jérémy Jun 18 '15 at 14:06
  • `option dhcp-server-identifier` isn't unique. Here by "chance" there is only "eth0" interface but it could have "wlan0" interface too which contain the same structure of lines. – Jérémy Jun 18 '15 at 14:07
  • So what would make that line unique? – Jahid Jun 18 '15 at 14:28
  • Can you add shell scripts to `/etc/dhcp/dhclient-exit-hooks.d/` ? – Mark Plotnick Jun 18 '15 at 18:05
  • If there is only one connection this line is unique, if you try to connect a second time it will create a new `lease{...}` @Jahid . Yes I can, I have root privileges @Mark Plotnick – Jérémy Jun 19 '15 at 07:52

1 Answers1

0

To more compatibility I finally opted for a simple solution which is to send the IP server like a string on broadcast every seconds. For that I use socat (because netcat can't send message to braodcast) my DHCP server run this script in background:

#!/bin/bash
interface="eth0"
IP=$(ifconfig $interface  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}')
Broadcast=$(ifconfig $interface  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f3 | awk '{ print $1}')
Port="5001"

while [ true ];
do
    sleep 1
    echo $IP | socat - UDP4-DATAGRAM:$Broadcast:$Port,so-broadcast
    #to listen: netcat -l -u $Broadcast -p $Port
done
exit 0
Jérémy
  • 1,790
  • 1
  • 24
  • 40