All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.objectos.net.LinuxNetworkAdapterFinder Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2016 Objectos, Fábrica de Software LTDA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package br.com.objectos.net;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import br.com.objectos.core.util.ImmutableList;
import br.com.objectos.core.util.ImmutableList.Builder;

/**
 * @author [email protected] (Marcio Endo)
 */
class LinuxNetworkAdapterFinder extends NetworkAdapterFinder {

  private static final Pattern DEV = Pattern.compile("^ *(.*):");

  LinuxNetworkAdapterFinder() {
  }

  @Override
  public List list() {
    Builder list = ImmutableList.builder();

    try (BufferedReader reader = buffer("/proc/net/dev")) {
      String line;
      while ((line = reader.readLine()) != null) {
        Matcher m = DEV.matcher(line);
        if (m.find()) {
          String name = m.group(1);
          list.add(toNetworkAdapter(name));
        }
      }
    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    return list.build();
  }

  @Override
  public NetworkAdapter named(String name) throws NetworkAdapterNotFoundException {
    try (BufferedReader reader = buffer("/sys/class/net/" + name + "/address")) {
      return new SimpleNetworkAdapter(
          name,
          HardwareAddress.fromString(reader.readLine()));
    } catch (IOException e) {
      throw NetworkAdapterNotFoundException.notFound(name, e);
    }
  }

  private BufferedReader buffer(String fileName) throws FileNotFoundException {
    FileReader in = new FileReader(fileName);
    return new BufferedReader(in);
  }

  private NetworkAdapter toNetworkAdapter(String name) throws FileNotFoundException, IOException {
    try (BufferedReader reader = buffer("/sys/class/net/" + name + "/address")) {
      return new SimpleNetworkAdapter(
          name,
          HardwareAddress.fromString(reader.readLine()));
    }
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy