001package voyeur.types; 002/*- 003 * ########################################################################## 004 * Local Area Network Voyeur 005 * %% 006 * Copyright (C) 2019 - 2022 Allen D. Ball 007 * %% 008 * Licensed under the Apache License, Version 2.0 (the "License"); 009 * you may not use this file except in compliance with the License. 010 * You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, software 015 * distributed under the License is distributed on an "AS IS" BASIS, 016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 017 * See the License for the specific language governing permissions and 018 * limitations under the License. 019 * ########################################################################## 020 */ 021import java.net.NetworkInterface; 022import java.net.SocketException; 023import java.util.ArrayList; 024import java.util.stream.Stream; 025 026import static java.util.stream.Collectors.joining; 027 028/** 029 * Hardware Address. 030 * 031 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball} 032 */ 033public class HardwareAddress { 034 private final ArrayList<Byte> list = new ArrayList<>(); 035 036 /** 037 * {@link NetworkInterface} constructor. 038 * 039 * @param netif The {@link NetworkInterface}. 040 * 041 * @throws SocketException If the hardware address canoot be read. 042 */ 043 public HardwareAddress(NetworkInterface netif) throws SocketException { 044 this(netif.getHardwareAddress()); 045 } 046 047 /** 048 * {@link String} constructor. 049 * 050 * @param string The {@link String} representation. 051 */ 052 public HardwareAddress(String string) { 053 Stream.of(string.split("[:]")) 054 .map(t -> Integer.valueOf(t, 16)) 055 .map(t -> t & 0xFF) 056 .forEach(t -> list.add(t.byteValue())); 057 } 058 059 /** 060 * {@code byte} array constructor. 061 * 062 * @param bytes The {@code byte} array representing the 063 * hardware address. 064 */ 065 public HardwareAddress(byte[] bytes) { 066 if (bytes != null) { 067 for (byte b : bytes) { 068 list.add(b); 069 } 070 } 071 } 072 073 @Override 074 public String toString() { 075 String string = 076 list.stream() 077 .map(t -> String.format("%02x", t)) 078 .collect(joining(":")); 079 080 return string; 081 } 082}