Set static ip if not obtained from DHCP (script) - linux

I work on embedded device with linux on it. I want to use DHCP client first, but if there will be no answer from DHCP Server I want to set static-default IP. I suppose it shouldn't be complicated, but I haven't found strict answer.
I'm thinking about 2 solutions (Unfortunately I can test them in few days):
I set static IP with ifconfig, then I call udhcpc. If udhcpc will not obtain new IP, old one will stay.
I can also first call udhcpc, wait a while and check if IP is obtained. But this is not nice for me. I wouldn't like to add any wait routines into startup.
BR
Bartek
I use udhcpc - something like:
udhcpc -n -f -i eth0
if ifconfig | grep -A1 eth0 | grep inet
then

dhclient should support fallback via lease declaration
have a look at the dhclient.conf man page.
Add something like this to your dhclient.conf
timeout 10;
lease {
interface "eth0";
fixed-address 10.0.0.10;
option subnet-mask 255.255.255.0;
renew 2 2022/1/1 00:00:01;
rebind 2 2022/1/1 00:00:01;
expire 2 2022/1/1 0:00:01;
}
or you can assign a second IP to the interface like /etc/network/interfaces
auto lo
iface lo inet loopback
iface eth0 inet dhcp
auto eth0:1
iface eth0:1 inet static
address 10.10.10.2
netmask 255.255.255.0

Although an old question, it might be worth noting here that Gentoo Linux has had this functionality for a long time (I've been using it since 2004). Gentoo's network config file (/etc/conf.d/net) allows for fallback IP addresses to be easily specified for any interface in the event that DHCP fails, e.g.:
modules="dhclient"
config_eth0="dhcp"
config_eth1="dhcp"
dhclient_eth1="nogateway"
fallback_eth0="apipa"
fallback_eth1="192.168.10.10/24"
fallback_routes_eth1="default via 192.168.10.1"
The solution Maurizio provided to use an alias like eth0:0 is fine in many (probably most) situations, but not all. I've run into one piece of software that does not consider eth0:0 to be a suitable substitute for eth0 when it is undefined due to no answer from DHCP, even though it is the same port. So a static fallback address is slightly superior to the alias solution.

Related

Raspbian : Force a wlan0 static ip [closed]

Closed. This question is not about programming or software development. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 6 months ago.
Improve this question
I would like to configure a wlan0 static ip and connect through it by ssh.
Here my /etc/network/interfaces :
source-directory /etc/network/interfaces.d
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
adress 192.168.0.2
netmask 255.255.255.0
auto wlan0
allow-hotplug wlan0
iface wlan0 inet static
address 192.168.100.102
netmask 255.255.255.0
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
When I do ifconfig my wlan0 and eth0 interfaces are correctly configured :
However, when I want to ssh my raspberry by wifi, my Wifi router give to my raspberry the ip : 192.168.100.116.
How can I force my Wifi router to give 192.168.100.102 to my rapsberry pi ?
Moreover, My Wifi router give to my raspberry sometimes 192.168.100.102 and sometimes 192.168.100.116
Don't know why
I experienced similar issues when I wanted to connect my Rasperry Pi 2 with Raspbian Jessie Lite in a headless configuration for access using SSH from my Windows 10 PC with PuTTY.
In my case it turned out that the Ahavi daemon (an implementation of zeroconf) conflicted with the DHCP and name server options of my router.
Raspbian Jessie and Raspbian Jessie Lite comes pre-configured with an Avahi and a DHCP client deamon for automated network configuration. In most situation this will probably work fine, but if not, things take a turn for the worse with unpredictable side-effects.
Instead of going too deep into any details (its really a long story) I will just summarize here what I did and why. There are too many possible issues and I dont want to push you into the wrong direction. Try it out. If it fails, look for another approach or leave a comment for clarification.
Now let's get your feet wet:
Try it first on a non-productive SD card with a fresh copy of Raspbian Jessie (for headless servers I prefer Raspbian Jessie Lite).
Start the Raspberry Pi with a keyboard and a monitor connected and login with user pi.
Start raspi-config with sudo raspi-config and make sure to turn on the SSH server (menue 7 Advanced Options -> A4 SSH).
Get your current IP address for eth0 with ifconfig.
Try to connect to this address over ethernet using ssh. In case you cant connect, resolve this issue first. You cant connect over WLAN at this stage.
In case your connection succeeds, you can do the rest of your configuration using this connection over ssh.
Purge the avahi-daemon
$ sudo apt-get purge avahi-daemon
Dont worry about the error message 'rmdir: failed to remove ‘/var/run/avahi-daemon’: Directory not empty'. This is related to a an empty socket and a pid file, that currently cannot be removed. You can ignore this message or remove the directory manually, but it wont hurt in case you just leave it.
$ sudo rm -r /var/run/avahi-daemon
Configure /etc/network/interfaces
It's important to know, that we need only one single change in this file. Open /etc/network/interfaces for changes with the editor of your choice (note: if you followed this steps 1:1 extended vim is not yet installed).
$ sudo nano /etc/network/interfaces
Add the line auto eth0 just before the existing line iface eth0 inet manual. That's all we have to do here is to here. After the changes the file should look like this:
# interfaces(5) file used by ifup(8) and ifdown(8)
# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'
# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet manual
allow-hotplug wlan0
iface wlan0 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
allow-hotplug wlan1
iface wlan1 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
Note: make sure to read and to understand the comments on top of the file!
Configure the DHCP client daemon
Next, as stated in the comments of the previously edited file, add the static ip configuration at the end of the configuration file for the DHCP client daemon.
It might sound silly to use a DHCP client if we are going to use static IP addresses anyway. However, when I tried to remove the DHCP client daemon I experienced new configuration and/or dependency issues. Finally I decided to keep as close to the standard configuration as possible and leave it as is.
The configuration is done at the very end in the file /etc/dhcpcd.conf (watch proper spelling). The last line in the file should read: 'nohook lookup-hostname'. So let's open the the file in the editor and scroll down to the bottom of the file.
$ sudo nano /etc/dhcpcd.conf
Add there the static ip definition. In my case the definitions at the of /etc/dhcpcd.conf look like this:
nohook lookup-hostname
# static ip configuration for eth0 and wlan0
interface eth0
static ip_address=192.168.1.61/24
static routers=192.168.1.1
static domain_name_servers=192.168.1.1 8.8.8.8
interface wlan0
static ip_address=192.168.1.62/24
static routers=192.168.1.1
static domain_name_servers=192.168.1.1 8.8.8.8
Note that the syntax is different from the syntax used in /etc/network/interfaces. For a full class C network the netmask must be provided in form of a /24 at the end of the IP address. For further details consult man dhcpcd.conf.
Reboot and test your configuration with eth0
After the next reboot you should have a reliable network configuration with static ip addresses. But remember, we are not yet finished and only eth0 will work. At this point even no IPv4 address will be shown for wlan0 if ifconfig is issued
In case it fails and you didn't do anything wrong so far (carefully check for typos), then you have another issue that must get fixed first; in this case this solution is probably not for you.
Configure WLAN
To configure WLAN we have to edit /etc/wpa_supplicant/wpa_supplicant.conf and add a network configuration to it.
In my case I'm using WPA/PSK for secure access and after modifying the country code and adding the network entry, the content of the file looks something like this:
country=CH
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
# home network; allow all valid ciphers
network={
ssid="home"
scan_ssid=1
key_mgmt=WPA-PSK
psk="very secret passphrase"
}
ssid="home" is the WLAN network name (SSID) of the WLAN router or access point.
scan_ssid=1 scans for hidden SSID's. This is usual practice but can slowdown the scan process.
key_mgmt=WPA-PSK defines that WPA pre-shared key management protocol will be used.
psk="very secret passphrase" defines your passphrase to access the router.
Replace the values assigned for ssid and psk with the real values for your secure WLAN access. There are several supported protocols, some requiring other and more options.
Consult man wpa_supplicant.conf for additional and more detailled information.
Reboot and test your configuration with wlan0
Now it's time to reboot and test wlan0. The ip address configured for wlan0 should now appear if ifconfig is issued.
If this is the case you should be able to access the Rasperry Pi using ssh with the IP address configured for wlan0.
I hope you are happy and everything works fine for you so far. If this is the case, I could stop writing here and leave you alone. But wait, there is more!
Two network connections, does that make sense?
If you connect to the Raspberry Pi from the same network over both, eth0 and wlan0 and issue an ifconfig to take a look at the transmitted and received packets or bytes, you will recognize, that even you connected to the IP for wlan0 most traffic is going through eth0.
I cant explain why this is the case, but obviously somehow the packets are routed along the faster path which sounds good so far.
However, I've seen rare situations where this behaviour was undesirable and slowed my connections down. Since I'm using my Raspberry Pi either near my router using a wired connection to eth0 or more distant from the router with no access to a cable using wlan0, I decided to stop wlan0 if a cable with an active connection to the router is attached to eth0.
To do this I created the script /home/pi/ifdown-wlan-if-not-needed.sh
#!/bin/sh
#### Shutdown wlan0
# Test eth0 for a cable attached and
# shutdown wlan0 if this is the case.
###
sleep 30
cable=$(cat /sys/class/net/eth0/carrier)
echo $cable
if [ "$cable" = "1" ]; then
sudo ifdown wlan0
fi
exit 0
Then I've set the script to executable
$ chmod +x /home/pi/ifdown-wlan-if-not-needed.sh
And added it for execution after reboot with crontab -e to the crontab of user pi.
#reboot /home/pi/ifdown-wlan-if-not-needed.sh
Name to IP address resolution
So far I have not yet addressed the name to IP address resolution problem. How this can be done best, depends on your network equipment and use case.
My router provides the ability to bind names to MAC addresses, hostnames and IPv4 adresses. However, for some reason none of these options really work. Some times it works by simply using the given name, other times the suffix .home is needed. Sometimes the names disappear from the list or no name resolution takes place even everything looks ok.
I finally defined the adresses in the C:\Windows\System32\drivers\etc\hosts file of my Windows PC and my Notebook. This is certainly not state of the art but works reliable and without hassle.
However, I cant guarantee that what I did works for you too, but I hope it brings you on the right track to get your problem solved. I've been using my configuration since the release of Raspbian Jessie about one year ago. It survived any updates without hassle so far.
Good luck!
Login on your router management interface and (if it has this feature, most do have it) reserve a DHCP address on the router for your selected client, so that the specific client always has the same IP address. See this article for more information.

OpenSIPs stun module require two IP addresses

I have to make a STUN server in OpenSIPs, and it says that I need to bind 2 IP addresses.
http://www.opensips.org/About/News0042
A STUN server uses 2 ips and 2 ports to create 4 sockets on which to listen or respond.
STUN requires 2 routable ip addresses
How can I enable two public IP addresses into one Linux server? I've searched all website, and failed to find the answer.
Several options.
Option 1.
You likely just need to use ifconfig from the command line to start
You can assign an additional static IP address to your NIC via the command line. Type ifconfig to get the name of your default adapter. It's typically "eth0". Then do add a secondary address to this adapter, the command is something like the following:
sudo ifconfig eth0:1 inet up netmask 255.255.255.0 192.168.1.55
Where 255.255.255.0 is the netmask of my 8-bit subnet and 192.16.1.55 is an existing IP address that no other device on my subnet is already using.
Option 2.
After you get your server up and running with Option 1, you likely need to find a way to get the IP address assigned by "ifconfig" to persist after a reboot. You could likely stick an ifconfig statement into one of your rc.init files. But most Linux skus have a formal way of configuring an interface with another /etc file. But this step varies between different flavors of Linux. On Ubuntu, this is all defined in the /etc/network/interfaces file. Add these three lines to the bottom of your existing file:
iface eth0:1 inet static
address 192.168.1.55
netmask 255.255.255.0
Option 3 (shameless plug)
Switch to Stuntman ( www.stunprotocol.org ) as your STUN server. Its default mode only requires one IP address to be present on the box. Most client usages of the STUN protocol don't require the second IP address unless to do NAT classification and behavior tests.

How can configure linux routing to send packets out one interface, over a bridge and into another interface on the same box

I'm trying to test a ethernet bridging device. I have multiple ethernet ports on a linux box. I would like to send packets out one interface, say eth0 with IP 192.168.1.1, to another interface, say eth1 with IP 192.168.1.2, on the same subnet.
I realize that normally you don't configure two interfaces on the same subnet, and if you do the kernel routes directly to each interface, rather than over the wire. How can I override this behavior, so that traffic to 192.168.1.2 goes out the 192.168.1.1 interface, and visa-versa?
Thanks in advance!
This is a guess, but I hope it is in the right direction.
Make more-specific routing table entries, along the lines of:
route add -host 192.168.1.2 dev eth0
route add -host 192.168.1.1 dev eth1
You may also need to fiddle with the accept_local configuration for both interfaces -- or the all setting. (Turning this on may make your machine more susceptible to IP source spoofing attacks; be sure you have good ingress firewall rules elsewhere to prevent trouble.) (See sysctl -a | grep accept_local for what I'm talking about.)
I think you need something like Mac-Vlan in your Linux. This cannot be done with NAT only. Read this: http://www.linuxjournal.com/article/7268.

configure ip alias and route, deal with network unavailable

I need to write a script to set ip address/mask/broadcast as an alias on eth0:0 plus set the default gateway.
This solution works:
ifconfig eth0:0 <ip> netmask <mask> up
ip route replace default via <ip>
but sometimes the second call gets an error "network unavailable".
Adding a sleep between them fixes it, but is unreliable. What is the proper way to wait for the network to be ready?
The best I came up with so far is retrying the ip call a couple times. This works, but feels ugly.
You could use ping -c1 -w on the gateway address in a loop until it comes up.
I think it is a bit strange that the interface isn't up when ifconfig returns.. I would try to skip ifconfig and only use the 'ip' command:
ip address add <ip>/<mask> dev eth0
ip route replace default via <ip>
This doesn't create a new alias interface eth0:0, it just configures an additional ip address on the primary interface, visible with 'ip address list'. I'm not sure if this works better, but it is worth a try.

Change IP address via shellscript on Slackware

In a shellscript, I'd like to set the IP of my box, run a command, then move to the next IP. The IPs are an entire C block.
The question is how do I set the IP of the box without editing a file? What command sets the IP on Slackware?
Thanks
As mentioned in other answers, you can use either the ifconfig command or the ip command. ip is a much more robust command, and I prefer to use it. A full script which loops through a full class C subnet adding the IP, doing stuff, then removing it follows. Note that it doesn't use .0 or .255, which are the network and broadcast addresses of the subnet. Also, when using the ip command to add or remove an address, it's good to include the mask width, as well (the /24 at the end of the address).
#!/bin/bash
SUBNET=192.168.135.
ETH=eth0
for i in {1..254}
do
ip addr add ${SUBNET}${i}/24 dev ${ETH}
# do whatever you want here
ip addr del ${SUBNET}${i}/24 dev ${ETH}
done
It should be something like: ifconfig eth0 192.168.0.42 up
Replace eth0 by the network interface of your network card, obviously adapt the ip address to your needs and the up is only necessary once, but doesn't hurt if you run it each time.
I don't know Slackware very well, I last used it over ten years ago. However, any mainstream Linux distribution should have either the 'ifconfig' program, or the 'ip' program or both. You will need to have root privilges, so either become root (e.g with su) or use the 'sudo' program if you know how. Let's do it with 'ip' first.
ip addr add 10.1.2.3 dev eth0
sets the device eth0 (usually the primary wired network adaptor) to have IP address 10.1.2.3. You can remove the address from this adaptor again when you're done with it...
ip addr del 10.1.2.3 dev eth0
ifconfig works a bit differently,
ifconfig eth0 10.1.2.3 netmask 255.255.255.0
again sets up device eth0, with IP address 10.1.2.3
Depending on what you want these addresses for, you may also need to know how to set up a manual route, so that your IP packets actually get delivered wherever they're going.
In one line, e.g.: ifconfig eth0 192.168.10.12 netmask 255.255.255.0

Resources