sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

OSError: [Errno 101] Network is unreachable

Tue Sep 22, 2020 12:41 pm

I was trying to use mqtt but get error OSError: [Errno 101] Network is unreachable

User avatar
neilgl
Posts: 7825
Joined: Sun Jan 26, 2014 8:36 pm
Location: Near The National Museum of Computing

Re: OSError: [Errno 101] Network is unreachable

Tue Sep 22, 2020 4:11 pm

Which OS are you using on the pi Raspberry Pi OS or something else and which mqtt have you installed (e.g. mosquitto)?

User avatar
DougieLawson
Posts: 42889
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK

Re: OSError: [Errno 101] Network is unreachable

Tue Sep 22, 2020 4:38 pm

Is the network active and working?

Get the results from

ip addr show
ip route
ping -c3 $(ip route | awk '/default/ {print $3}')
ping -c3 8.8.8.8
ping -c3 google.com
cat /etc/resolv.conf
Languages using left-hand whitespace for syntax are ridiculous

DMs sent on https://twitter.com/DougieLawson or LinkedIn will be answered next month.
Fake doctors - are all on my foes list.

The use of crystal balls and mind reading is prohibited.

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 1:45 am

hi, i am using Raspbian and for MQTT mosquitto.

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 1:47 am

neilgl wrote:
Tue Sep 22, 2020 4:11 pm
Which OS are you using on the pi Raspberry Pi OS or something else and which mqtt have you installed (e.g. mosquitto)?
raspbian operating system and mosquitto for mqtt

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 1:53 am

DougieLawson wrote:
Tue Sep 22, 2020 4:38 pm
Is the network active and working?

Get the results from

ip addr show
ip route
ping -c3 $(ip route | awk '/default/ {print $3}')
ping -c3 8.8.8.8
ping -c3 google.com
cat /etc/resolv.conf
ping is working fine for me there is no packet loss.

pi@raspberrypi:~ $ cat /etc/resolv.conf
# Generated by resolvconf
nameserver 192.168.1.1
pi@raspberrypi:~ $ ip route
default via 192.168.1.1 dev wlan0 proto dhcp src 192.168.1.108 metric 303
192.168.1.0/24 dev wlan0 proto dhcp scope link src 192.168.1.108 metric 303
pi@raspberrypi:~ $ ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN group default qlen 1000
link/ether b8:27:eb:44:43:87 brd ff:ff:ff:ff:ff:ff
3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether b8:27:eb:11:16:d2 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.108/24 brd 192.168.1.255 scope global dynamic noprefixroute wlan0
valid_lft 86167sec preferred_lft 75367sec
inet6 fe80::5b21:4a96:e6ee:9a7a/64 scope link
valid_lft forever preferred_lft forever

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 2:38 am

this is the error :

%Run fclient.py
Traceback (most recent call last):
File "/home/pi/py-sds011/fclient.py", line 73, in <module>
client.connect("test.mosquitto.org", 1883, 60)
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/client.py", line 937, in connect
return self.reconnect()
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/client.py", line 1071, in reconnect
sock = self._create_socket_connection()
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/client.py", line 3522, in _create_socket_connection
return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
File "/usr/lib/python3.7/socket.py", line 727, in create_connection
raise err
File "/usr/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
OSError: [Errno 101] Network is unreachable
>>> %Run client.py
Traceback (most recent call last):
File "/home/pi/py-sds011/client.py", line 61, in <module>
client.connect("test.mosquitto.org", 1883, 60)
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/client.py", line 937, in connect
return self.reconnect()
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/client.py", line 1071, in reconnect
sock = self._create_socket_connection()
File "/home/pi/.local/lib/python3.7/site-packages/paho/mqtt/client.py", line 3522, in _create_socket_connection
return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
File "/usr/lib/python3.7/socket.py", line 727, in create_connection
raise err
File "/usr/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
OSError: [Errno 101] Network is unreachable


I have attached my CLIENT code as well :

# MQTT Client demo
# Continuously monitor two different MQTT topics for data,
# check if the received data matches two predefined 'commands'
import board
import busio
import adafruit_ccs811
import paho.mqtt.client as mqtt
import Adafruit_DHT
import time
import datetime
import csv
from sds011 import *

csvfile = "Final.csv"

sensor = SDS011("/dev/ttyUSB0")
sensor.sleep(sleep=False)
time.sleep(10)
pmt_2_5, pmt_10 = sensor.query()

i2c = busio.I2C(board.SCL, board.SDA)
ccs811 = adafruit_ccs811.CCS811(i2c)

# Wait for the sensor to be ready
while not ccs811.data_ready:
pass
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))

# Subscribing in on_connect() - if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("CoreElectronics/test")
client.subscribe("CoreElectronics/topic")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))

while True:
msg.payload == "Hello"

print(f" PMT2.5: {pmt_2_5} μg/m3 ", end='')
print(f"PMT10 : {pmt_10} μg/m3")
sensor.sleep(sleep=True)

print("CO2: {} PPM, TVOC: {} PPB".format(ccs811.eco2, ccs811.tvoc))

humidity,temperature= Adafruit_DHT.read_retry(Adafruit_DHT.DHT11,4)
if humidity is not None and temperature is not None:
humidity= round(humidity,2)
temperature= round(temperature,2)
print ('Temperature = {0:0.1f}*C Humidity = {1:0.1f}%'.format(temperature, humidity))

timeC = time.strftime("%I")+':' +time.strftime("%M")+':'+time.strftime("%S")
data = [timeC,temperature,humidity,ccs811.eco2,ccs811.tvoc,pmt_2_5, pmt_10]

with open(csvfile, "a")as output:
writer = csv.writer(output, delimiter=",", lineterminator = '\n')
writer.writerow(data)
time.sleep(60)

if msg.payload == "World!":
print("print'can not connect to the server'")
# Do something else


# Create an MQTT client and attach our routines to it.
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("test.mosquitto.org", 1883, 60)

# Process network traffic and dispatch callbacks. This will also handle
# reconnecting. Check the documentation at
# https://github.com/eclipse/paho.mqtt.python
# for information on how to use other loop*() functions
client.loop_forever()

User avatar
neilgl
Posts: 7825
Joined: Sun Jan 26, 2014 8:36 pm
Location: Near The National Museum of Computing

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 8:10 am

Can you re-post your script(s) using Code tags so we can see the indentation? And are there two scripts? (fclient.py and client.py).
And what was the result of ping google.com
Last edited by neilgl on Thu Sep 24, 2020 8:22 am, edited 1 time in total.

User avatar
rpdom
Posts: 23522
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 8:21 am

sach wrote:
Thu Sep 24, 2020 1:53 am
ping is working fine for me there is no packet loss.
It looks like your DNS lookup is being provided by your router at 192.168.1.1 (from your resolv.conf).
Also the router is the default gateway, which should be correct.

Did all three ping commands work?

The first is to confirm that you Pi can see your router.

The second is to confirm your traffic is being routed to the internet correctly.

The third is to confirm that DNS lookup for external sites is working correctly.

Code: Select all

File "/usr/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
OSError: [Errno 101] Network is unreachable
That is the important part of the error message, which I suspect is caused by this line of code

Code: Select all

client.connect("test.mosquitto.org", 1883, 60)
Is that the correct hostname to connect to?

What do you get with these commands?

Code: Select all

host test.mosquitto.org
ping -c 1 test.mosquitto.org
Unreadable squiggle

User avatar
neilgl
Posts: 7825
Joined: Sun Jan 26, 2014 8:36 pm
Location: Near The National Museum of Computing

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 8:25 am

If you have installed mosquitto clients [install if needed], try this from a terminal (not IDLE, mu, Thonny)

Code: Select all

 mosquitto_sub -h test.mosquitto.org -t "#" -v

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 1:12 pm

rpdom wrote:
Thu Sep 24, 2020 8:21 am
sach wrote:
Thu Sep 24, 2020 1:53 am
ping is working fine for me there is no packet loss.
It looks like your DNS lookup is being provided by your router at 192.168.1.1 (from your resolv.conf).
Also the router is the default gateway, which should be correct.

Did all three ping commands work?

The first is to confirm that you Pi can see your router.

The second is to confirm your traffic is being routed to the internet correctly.

The third is to confirm that DNS lookup for external sites is working correctly.

Code: Select all

File "/usr/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
OSError: [Errno 101] Network is unreachable
That is the important part of the error message, which I suspect is caused by this line of code

Code: Select all

client.connect("test.mosquitto.org", 1883, 60)
Is that the correct hostname to connect to?

What do you get with these commands?

Code: Select all

host test.mosquitto.org
ping -c 1 test.mosquitto.org
hi, i have attached the ping statistics below:

$ ping -c3 $(ip route | awk '/default/ {print $3}')
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=2.48 ms
64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=2.17 ms
64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=1.75 ms

--- 192.168.1.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 5ms
rtt min/avg/max/mdev = 1.754/2.135/2.483/0.300 ms
pi@raspberrypi:~ $ ping -c3 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=11.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=119 time=11.10 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=119 time=11.2 ms

--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 4ms
rtt min/avg/max/mdev = 11.166/11.653/11.980/0.362 ms
pi@raspberrypi:~ $ ping -c3 google.com
PING google.com (142.250.66.206) 56(84) bytes of data.
64 bytes from syd09s23-in-f14.1e100.net (142.250.66.206): icmp_seq=1 ttl=119 time=9.99 ms
64 bytes from syd09s23-in-f14.1e100.net (142.250.66.206): icmp_seq=2 ttl=119 time=12.4 ms
64 bytes from syd09s23-in-f14.1e100.net (142.250.66.206): icmp_seq=3 ttl=119 time=10.3 ms

--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 5ms
rtt min/avg/max/mdev = 9.987/10.905/12.416/1.083 ms
pi@raspberrypi:~ $


host test.mosquitto.org
test.mosquitto.org has address 5.196.95.208
test.mosquitto.org has IPv6 address 2001:41d0:a:fed0::1

pi@raspberrypi:~ $ ping -c 1 test.mosquitto.org
PING test.mosquitto.org (5.196.95.208) 56(84) bytes of data.
64 bytes from ks2.ral.me (5.196.95.208): icmp_seq=1 ttl=53 time=305 ms

--- test.mosquitto.org ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 304.504/304.504/304.504/0.000 ms
Last edited by sach on Fri Sep 25, 2020 1:30 am, edited 1 time in total.

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 1:15 pm

neilgl wrote:
Thu Sep 24, 2020 8:25 am
If you have installed mosquitto clients [install if needed], try this from a terminal (not IDLE, mu, Thonny)

Code: Select all

 mosquitto_sub -h test.mosquitto.org -t "#" -v
Hi, from where i can install mosquitto clients?

User avatar
neilgl
Posts: 7825
Joined: Sun Jan 26, 2014 8:36 pm
Location: Near The National Museum of Computing

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 1:46 pm

Code: Select all

sudo apt install -y mosquitto mosquitto-clients

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 1:59 pm

neilgl wrote:
Thu Sep 24, 2020 8:10 am
Can you re-post your script(s) using Code tags so we can see the indentation? And are there two scripts? (fclient.py and client.py).
And what was the result of ping google.com
I have two scripts fclient.py and client.py. i did some changes in client.py to get rid of error and made new script fclient. they almost same.

code is for client.py

Code: Select all

# MQTT Client demo
# Continuously monitor two different MQTT topics for data,
# check if the received data matches two predefined 'commands'
import board
import busio
import adafruit_ccs811
import paho.mqtt.client as mqtt
import Adafruit_DHT
import time
import datetime
from sds011 import *

#Taking data from the dust sensor 
sensor = SDS011("/dev/ttyUSB0")
sensor.sleep(sleep=False)
time.sleep(10)
pmt_2_5, pmt_10 = sensor.query()

#Monitoring data from CCS811 (Dust sensor) via I2C
i2c = busio.I2C(board.SCL, board.SDA)
ccs811 = adafruit_ccs811.CCS811(i2c)

 # Wait for the sensor to be ready
while not ccs811.data_ready:
    pass
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
 
    # Subscribing in on_connect() - if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("CoreElectronics/test")
    client.subscribe("CoreElectronics/topic")
 
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

    while True:
        msg.payload == "Hello"
        
        print(f"    PMT2.5: {pmt_2_5} μg/m3    ", end='')
        print(f"PMT10 : {pmt_10} μg/m3")
        sensor.sleep(sleep=True)
        
        print("CO2: {} PPM, TVOC: {} PPB".format(ccs811.eco2, ccs811.tvoc))
  
        humidity,temperature= Adafruit_DHT.read_retry(Adafruit_DHT.DHT11,4)
        if humidity is not None and temperature is not None:
            humidity= round(humidity,2)
            temperature= round(temperature,2)
            print ('Temperature = {0:0.1f}*C  Humidity = {1:0.1f}%'.format(temperature, humidity))

    if msg.payload == "World!":
        print("print'can not connect to the server'")
        # Do something else
 
# Create an MQTT client and attach our routines to it.
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
 
client.connect("test.mosquitto.org", 1883, 60)
 
# Process network traffic and dispatch callbacks. This will also handle
# reconnecting. Check the documentation at
# https://github.com/eclipse/paho.mqtt.python
# for information on how to use other loop*() functions
client.loop_forever()

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 2:11 pm

sach wrote:
Thu Sep 24, 2020 1:15 pm
neilgl wrote:
Thu Sep 24, 2020 8:25 am
If you have installed mosquitto clients [install if needed], try this from a terminal (not IDLE, mu, Thonny)

Code: Select all

 mosquitto_sub -h test.mosquitto.org -t "#" -v
i tried running that in terminal but nothing happened.


Hi, from where i can install mosquitto clients?

User avatar
neilgl
Posts: 7825
Joined: Sun Jan 26, 2014 8:36 pm
Location: Near The National Museum of Computing

Re: OSError: [Errno 101] Network is unreachable

Thu Sep 24, 2020 4:00 pm

OK that server seems to be down. In one terminal start a sub

Code: Select all

mosquitto_sub -t 'F215166/test' -v -h mqtt.eclipse.org
. Then in another terminal publish

Code: Select all

mosquitto_pub -t 'F215166/test' -h mqtt.eclipse.org -m "$(date +%Y%m%d)"
You should see the topic appear in the sub window F215166/test 20200924

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Fri Sep 25, 2020 1:18 am

neilgl wrote:
Thu Sep 24, 2020 4:00 pm
OK that server seems to be down. In one terminal start a sub

Code: Select all

mosquitto_sub -t 'F215166/test' -v -h mqtt.eclipse.org
. Then in another terminal publish

Code: Select all

mosquitto_pub -t 'F215166/test' -h mqtt.eclipse.org -m "$(date +%Y%m%d)"
You should see the topic appear in the sub window F215166/test 20200924
yup this one works. how can i use this in my code?

User avatar
neilgl
Posts: 7825
Joined: Sun Jan 26, 2014 8:36 pm
Location: Near The National Museum of Computing

Re: OSError: [Errno 101] Network is unreachable

Fri Sep 25, 2020 7:01 am

In your code, connect to mqtt.eclipse.org instead of test.mosquitto.org

sach
Posts: 13
Joined: Sat Aug 22, 2020 12:41 am

Re: OSError: [Errno 101] Network is unreachable

Fri Sep 25, 2020 12:43 pm

neilgl wrote:
Fri Sep 25, 2020 7:01 am
In your code, connect to mqtt.eclipse.org instead of test.mosquitto.org
thanks mate its working now :D

User avatar
neilgl
Posts: 7825
Joined: Sun Jan 26, 2014 8:36 pm
Location: Near The National Museum of Computing

Re: OSError: [Errno 101] Network is unreachable

Fri Sep 25, 2020 12:46 pm

Good one!

Return to “Beginners”