aramperes / nut-rs

rups: A Network UPS Tools (NUT) implementation in Rust.

Home Page:https://crates.io/crates/rups

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Connection refused

ohuu opened this issue · comments

Even though all the connection settings are correct and I can use upsc to query my UPS I get Connection refused when creating a new connection using the example code.

use dotenvy::dotenv;

use rups::blocking::Connection;
use rups::{Auth, ConfigBuilder};

use std::convert::TryInto;
use std::env;

fn main() -> rups::Result<()> {
    // load environment variables from .env file
    dotenv().expect(".env file not found");

    let host = env::var("NUT_HOST").unwrap_or_else(|_| "localhost".into());
    let port = env::var("NUT_PORT")
        .ok()
        .map(|s| s.parse::<u16>().ok())
        .flatten()
        .unwrap_or(3493);

    let username = env::var("NUT_USER").ok();
    let password = env::var("NUT_PASSWORD").ok();
    let auth = username.map(|username| Auth::new(username, password));

    let config = ConfigBuilder::new()
        .with_host((host, port).try_into().unwrap_or_default())
        .with_auth(auth)
        .with_debug(true) // Turn this on for debugging network chatter
        .build();

    let mut conn = Connection::new(&config)?;

    // Print a list of all UPS devices
    println!("Connected UPS devices:");
    for (name, description) in conn.list_ups()? {
        println!("\t- Name: {}", name);
        println!("\t  Description: {}", description);

        // List UPS variables (key = val)
        println!("\t  Variables:");
        for var in conn.list_vars(&name)? {
            println!("\t\t- {}", var);
        }
    }

    Ok(())
}

To be specific I receive the following error:

Error: Io(Os { code: 111, kind: ConnectionRefused, message: "Connection refused" })

I managed to get this to work but I needed to change NUT_HOST to 127.0.0.1 instead of localhost. I'm not sure why though!

It's probably because localhost resolves to ::1 (ipv6) instead of 127.0.0.1 (ipv4)

It's common for tools to alias localhost to try both instead of relying on the host DNS resolver. That could be added to the library