Compare commits

...

4 Commits

Author SHA1 Message Date
Michal 8f295251e0 upravy a editovani connection 2025-02-24 20:04:32 +01:00
Michal 3b6717a580 přidany propojení mezi objekty včetně zobrazovaní trafficu 2025-02-24 10:48:19 +01:00
Michal 01d3a02b0d pridáno tlačítko na SNMP test 2025-02-18 22:17:38 +01:00
Michal 9b78c61936 SNMP 2025-02-18 18:40:00 +01:00
11 changed files with 1000 additions and 1 deletions

View File

@ -104,8 +104,30 @@ public class Message implements Serializable {
// C->S: klient posila požadavek na smazaní udalostí
public static final int DELETE_LOG = 113;
// C->S: klient si vyžádal SNMP informace o bojektu
public static final int SNMP_OBJECT_INFO = 114;
// C->S: klient si vyžádal SNMP informace o interface objektu
public static final int SNMP_OBJECT_INTERFACE = 115;
// C->S: klient testuje snmp nastavení
// S->C: server odesila vysledek testu
public static final int SNMP_TEST = 116;
// C->S: klient si vyzadal SNMP seznam rozhrani objektu
// S->C: klient odpovida seznam interfacu
public static final int SNMP_CONNECTION_INTERFACE = 117;
// C->S: klient zasila na server informaci o novem spojeni
// S->C: server rozesila nove spojeni
public static final int CONNECTION_NEW = 118;
// S->C: server posila klientu trafic informaci
public static final int TRAFFIC = 119;
// C->S: klient posila upravene spoení
// S->C: server posila upravene spojeni
public static final int CONNECTION_UPDATE = 120;

View File

@ -0,0 +1,153 @@
package jnet.lib.object;
import java.io.Serializable;
public class Connection implements Serializable {
public static final int TYPE_OTHER = 0;
public static final int TYPE_GE = 1;
public static final int TYPE_FE = 2;
public static final int TYPE_E = 3;
public static final int TYPE_10GE = 4;
public static final int TYPE_100M_FIBER = 5;
public static final int TYPE_1G_FIBER = 6;
public static final int TYPE_10G_FIBER = 7;
public static final int TYPE_WIRELESS = 8;
public static final int TYPE_TUNEL = 9;
public static final int TYPE_VLAN = 10;
private int id;
private int sourceObj;
private int destinationObj;
private int type;
private int map;
private boolean readTraffic;
private int trafficObject;
private int trafficIface;
private long rx;
private long tx;
public Connection(int id, int sourceObj, int destinationObj, int type, int map, boolean readTraffic, int trafficObject, int trafficIface) {
this.id = id;
this.sourceObj = sourceObj;
this.destinationObj = destinationObj;
this.type = type;
this.map = map;
this.readTraffic = readTraffic;
this.trafficObject = trafficObject;
this.trafficIface = trafficIface;
this.rx = 0;
this.tx = 0;
}
public Connection(int sourceObj, int destinationObj, int type, int map, boolean readTraffic, int trafficObject, int trafficIface) {
this.sourceObj = sourceObj;
this.destinationObj = destinationObj;
this.type = type;
this.map = map;
this.readTraffic = readTraffic;
this.trafficObject = trafficObject;
this.trafficIface = trafficIface;
this.rx = 0;
this.tx = 0;
}
public Connection() {
this.rx = 0;
this.tx = 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getSourceObj() {
return sourceObj;
}
public void setSourceObj(int sourceObj) {
this.sourceObj = sourceObj;
}
public int getDestinationObj() {
return destinationObj;
}
public void setDestinationObj(int destinationObj) {
this.destinationObj = destinationObj;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getMap() {
return map;
}
public void setMap(int map) {
this.map = map;
}
public boolean isReadTraffic() {
return readTraffic;
}
public void setReadTraffic(boolean readTraffic) {
this.readTraffic = readTraffic;
}
public int getTrafficObject() {
return trafficObject;
}
public void setTrafficObject(int trafficObject) {
this.trafficObject = trafficObject;
}
public int getTrafficIface() {
return trafficIface;
}
public void setTrafficIface(int trafficIface) {
this.trafficIface = trafficIface;
}
public String getRx() {
return convertBps(rx);
}
public void setRx(long rx) {
this.rx = rx;
}
public String getTx() {
return convertBps(tx);
}
public void setTx(long tx) {
this.tx = tx;
}
public static String convertBps(long Bps) {
double bitsPerSec = Bps * 8.0; // Převod na bity za sekundu jako double pro přesnost
if (bitsPerSec >= 1_000_000_000) {
return String.format("%.2f Gbps", bitsPerSec / 1_000_000_000.0);
} else if (bitsPerSec >= 1_000_000) {
return String.format("%.2f Mbps", bitsPerSec / 1_000_000.0);
} else if (bitsPerSec >= 1_000) {
return String.format("%.2f Kbps", bitsPerSec / 1_000.0);
} else {
return String.format("%.0f bps", bitsPerSec); // Zobrazení bez desetinných míst pro malé hodnoty
}
}
}

View File

@ -16,6 +16,7 @@ public class Event implements Serializable{
public static final int TYPE_SNMP = 2;
public static final int TYPE_INFO = 3;
public static final int TYPE_PING_OFF = 4;
public static final int TYPE_PING_ON = 5;
public Event(int id, int object, long start, long end, String description, int type) {
this.id = id;

View File

@ -10,14 +10,16 @@ public class Map implements Serializable {
private String name;
private boolean lock;
private ArrayList<MapObject> objects;
private ArrayList<Connection> connection;
private int status;
public Map(int id, String name, boolean lock, ArrayList<MapObject> objects) {
public Map(int id, String name, boolean lock, ArrayList<MapObject> objects, ArrayList<Connection> connection) {
this.id = id;
this.name = name;
this.lock = lock;
this.status = Status.NA;
this.objects = objects;
this.connection = connection;
}
@ -59,6 +61,16 @@ public class Map implements Serializable {
this.objects = objects;
}
public ArrayList<Connection> getConnection() {
return connection;
}
public void setConnection(ArrayList<Connection> connection) {
this.connection = connection;
}
public int getStatus() {
if (getObjects().isEmpty()) {
return Status.NA;

View File

@ -1,6 +1,7 @@
package jnet.lib.object;
import java.io.Serializable;
import org.snmp4j.mp.SnmpConstants;
public class SnmpProfile implements Serializable {
@ -11,6 +12,11 @@ public class SnmpProfile implements Serializable {
private String port;
private String communityRead;
private String communityWrite;
private static final int version1 = SnmpConstants.version1;
private static final int version2c = SnmpConstants.version2c;
private static final int version3 = SnmpConstants.version3;
public SnmpProfile(int id, String name, int version, String port, String communityRead, String communityWrite) {
this.id = id;

View File

@ -0,0 +1,74 @@
package jnet.lib.snmp;
import java.io.Serializable;
public class DeviceInfo implements Serializable{
private String sysName;
private String sysDescr;
private String sysUptime;
private String sysContact;
private String sysLocation;
private String sysObjectID;
public DeviceInfo(String sysName, String sysDescr, String sysUptime, String sysContact, String sysLocation, String sysObjectID) {
this.sysName = sysName;
this.sysDescr = sysDescr;
this.sysUptime = sysUptime;
this.sysContact = sysContact;
this.sysLocation = sysLocation;
this.sysObjectID = sysObjectID;
}
public String getSysName() {
return sysName;
}
public void setSysName(String sysName) {
this.sysName = sysName;
}
public String getSysDescr() {
return sysDescr;
}
public void setSysDescr(String sysDescr) {
this.sysDescr = sysDescr;
}
public String getSysUptime() {
return sysUptime;
}
public void setSysUptime(String sysUptime) {
this.sysUptime = sysUptime;
}
public String getSysContact() {
return sysContact;
}
public void setSysContact(String sysContact) {
this.sysContact = sysContact;
}
public String getSysLocation() {
return sysLocation;
}
public void setSysLocation(String sysLocation) {
this.sysLocation = sysLocation;
}
public String getSysObjectID() {
return sysObjectID;
}
public void setSysObjectID(String sysObjectID) {
this.sysObjectID = sysObjectID;
}
}

View File

@ -0,0 +1,104 @@
package jnet.lib.snmp;
import java.io.Serializable;
public class Interface implements Serializable {
private int id;
private String description;
private String operStatus;
private String speed;
private String type;
private String macAddress;
private String adminStatus;
private String lastChangeTime;
public Interface(int id, String description, String operStatus, String speed, String type, String macAddress, String adminStatus, String lastChangeTime) {
this.id = id;
this.description = description;
this.operStatus = operStatus;
this.speed = speed;
this.type = type;
this.macAddress = macAddress;
this.adminStatus = adminStatus;
this.lastChangeTime = lastChangeTime;
}
@Override
public String toString() {
return "Interface ID: " + id + "\n"
+ "Description: " + description + "\n"
+ "Operational Status: " + operStatus + "\n"
+ "Speed: " + speed + "\n"
+ "Type: " + type + "\n"
+ "MAC Address: " + macAddress + "\n"
+ "Administrative Status: " + adminStatus + "\n"
+ "Last Link Change: " + lastChangeTime + "\n";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOperStatus() {
return operStatus;
}
public void setOperStatus(String operStatus) {
this.operStatus = operStatus;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public String getAdminStatus() {
return adminStatus;
}
public void setAdminStatus(String adminStatus) {
this.adminStatus = adminStatus;
}
public String getLastChangeTime() {
return lastChangeTime;
}
public void setLastChangeTime(String lastChangeTime) {
this.lastChangeTime = lastChangeTime;
}
}

View File

@ -0,0 +1,154 @@
package jnet.lib.snmp;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class SNMPDeviceInfo {
private Snmp snmp;
private String address;
private String community;
private int version;
// SNMP OID pro základní informace
private static final OID SYS_NAME_OID = new OID("1.3.6.1.2.1.1.5.0");
private static final OID SYS_DESCR_OID = new OID("1.3.6.1.2.1.1.1.0");
private static final OID SYS_UPTIME_OID = new OID("1.3.6.1.2.1.1.3.0");
private static final OID SYS_CONTACT_OID = new OID("1.3.6.1.2.1.1.4.0");
private static final OID SYS_LOCATION_OID = new OID("1.3.6.1.2.1.1.6.0");
private static final OID SYS_OBJECT_ID_OID = new OID("1.3.6.1.2.1.1.2.0");
// OID databáze vyrobcu
private static final Map<String, String> DEVICE_OID_MAP = new HashMap<>();
static {
DEVICE_OID_MAP.put("1.3.6.1.4.1.9", "Cisco");
DEVICE_OID_MAP.put("1.3.6.1.4.1.11", "Hewlett-Packard (HP)");
DEVICE_OID_MAP.put("1.3.6.1.4.1.14988", "Mikrotik");
DEVICE_OID_MAP.put("1.3.6.1.4.1.41112.1.3.1", "Ubiquiti Networks");
DEVICE_OID_MAP.put("1.3.6.1.4.1.259.10.1.43.101", "EdgeCore");
DEVICE_OID_MAP.put("1.3.6.1.4.1.11863.5.1048577", "TP-Link");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.43", "Lexmark");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.311", "Microsoft");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.3224", "Fortinet");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.8072", "Net-SNMP");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.2021", "Linux Host");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.171", "D-Link");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.12148", "MikroTik");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.2636", "Juniper Networks");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.674", "Dell");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.2352", "Allied Telesis");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.807", "IBM");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.562", "Alcatel");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.14988", "Ubiquiti Networks");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.22610", "Ruckus Wireless");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.318", "APC (Schneider Electric)");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.2011", "Huawei");
// DEVICE_OID_MAP.put("1.3.6.1.4.1.4826", "Opengear");
}
public SNMPDeviceInfo(String ip, String port, String community, int version) throws IOException {
this.address = ip + "/" + port; // Přidání SNMP portu
this.community = community;
this.version = version;
TransportMapping<UdpAddress> transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();
}
/**
* Získání základních informací o zařízení.
*/
public DeviceInfo getDeviceInfo() throws IOException {
DeviceInfo di = new DeviceInfo(
getAsString(SYS_NAME_OID),
getAsString(SYS_DESCR_OID),
getAsString(SYS_UPTIME_OID),
getAsString(SYS_CONTACT_OID),
getAsString(SYS_LOCATION_OID),
getDeviceVendor()
);
return di;
}
/**
* Získá sysObjectID a přeloží na výrobce
*
* @return Výrobce nebo "Neznámý" + OID
* @throws IOException
*/
public String getDeviceVendor() throws IOException {
String sysObjectID = getAsString(SYS_OBJECT_ID_OID);
// Překlad OID na výrobce
for (String oidPrefix : DEVICE_OID_MAP.keySet()) {
if (sysObjectID.startsWith(oidPrefix)) {
return DEVICE_OID_MAP.get(oidPrefix);
}
}
return "Neznámý výrobce (" + sysObjectID + ")";
}
/**
* Získání hodnoty SNMP OID jako String.
*/
private String getAsString(OID oid) throws IOException {
CommunityTarget target = createTarget();
PDU pdu = new PDU();
pdu.add(new VariableBinding(oid));
pdu.setType(PDU.GET);
ResponseEvent event = snmp.get(pdu, target);
if (event != null && event.getResponse() != null) {
return event.getResponse().get(0).getVariable().toString();
} else {
return "No response";
}
}
/**
* Převede SNMP sysUpTime (setiny sekundy) na čitelný formát D HH:MM:SS
*
* @param sysUpTime setiny sekundy (centiseconds)
* @return čitelný uptime
*/
private static String formatUptime(String sysUpTime) {
System.out.println("jnet.lib.snmp.SNMPDeviceInfo.formatUptime() " +sysUpTime);
try {
long centiseconds = Long.parseLong(sysUpTime);
long totalSeconds = centiseconds / 100;
long days = totalSeconds / 86400;
long hours = (totalSeconds % 86400) / 3600;
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
return String.format("%d dní, %02d:%02d:%02d", days, hours, minutes, seconds);
} catch (NumberFormatException e) {
return "Neplatný uptime";
}
}
/**
* Vytvoření SNMP cíle (target).
*/
private CommunityTarget createTarget() {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(this.community));
target.setAddress(new UdpAddress(this.address));
target.setVersion(this.version);
target.setRetries(2);
target.setTimeout(1500);
return target;
}
}

View File

@ -0,0 +1,280 @@
package jnet.lib.snmp;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class SNMPInterfaceScanner {
private Snmp snmp;
private String address;
private String community;
private int version;
// OID pro rozhraní v IF-MIB
private static final String IF_INDEX_OID = "1.3.6.1.2.1.2.2.1.1"; // ifIndex
private static final String IF_DESCR_OID = "1.3.6.1.2.1.2.2.1.2"; // ifDescr
private static final String IF_SPEED_OID = "1.3.6.1.2.1.2.2.1.5"; // speed
private static final String IF_TYPE_OID = "1.3.6.1.2.1.2.2.1.3"; // ifType
private static final String IF_MAC_OID = "1.3.6.1.2.1.2.2.1.3"; // mac
private static final String IF_STATUS_OID = "1.3.6.1.2.1.2.2.1.8"; // ifOperStatus
private static final String IF_STATUS_ADM_OID = "1.3.6.1.2.1.2.2.1.7"; // adminStatus
private static final String IF_LAST_CHANGE_OID = "1.3.6.1.2.1.2.2.1.9"; // lastchange
public SNMPInterfaceScanner(String address, String port, String community, int version) throws IOException {
this.address = address + "/" + port;
this.community = community;
this.version = version;
TransportMapping<UdpAddress> transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();
}
/**
* Získání detailních informací o všech interfaces
*
* @throws IOException
*/
public List<Interface> scanInterfaces() throws IOException {
List<Interface> list = new ArrayList<>();
CommunityTarget target = createTarget();
OID oid = new OID(IF_INDEX_OID); // Start na ifIndex
boolean finished = false;
while (!finished) {
PDU pdu = new PDU();
pdu.add(new VariableBinding(oid));
pdu.setType(PDU.GETNEXT);
ResponseEvent response = snmp.send(pdu, target);
if (response == null || response.getResponse() == null) {
System.out.println("Žádná odpověď od SNMP agenta.");
break;
}
VariableBinding vb = response.getResponse().get(0);
OID nextOid = vb.getOid();
// Pokud jsme mimo tabulku, ukončit cyklus
if (!nextOid.startsWith(new OID(IF_INDEX_OID))) {
finished = true;
continue;
}
int ifIndex = vb.getVariable().toInt();
String ifDescr = getSnmpValue(IF_DESCR_OID + "." + ifIndex, target);
String ifType = getSnmpValue(IF_TYPE_OID + "." + ifIndex, target);
String ifStatus = getSnmpValue(IF_STATUS_OID + "." + ifIndex, target);
String ifSpeed = getSnmpValue(IF_SPEED_OID + "." + ifIndex, target);
String ifMac = getSnmpValue(IF_MAC_OID + "." + ifIndex, target);
String ifStatusAdm = getSnmpValue(IF_STATUS_ADM_OID + "." + ifIndex, target);
String ifLastChange = getSnmpValue(IF_LAST_CHANGE_OID + "." + ifIndex, target);
list.add(new Interface(
ifIndex, // index
ifDescr, // description
getInterfaceStatus(ifStatus), // operStatus
formatIfSpeed(Long.parseLong(ifSpeed)), // speed
getInterfaceType(ifType), // type
ifMac, //mac
convertIfAdminStatus(ifStatusAdm), //adminStatus
ifLastChange // lastChange
));
// Posuneme OID na další položku
oid = nextOid;
}
snmp.close();
return list;
}
/**
* Pomocná metoda pro vytvoření SNMP cíle (target)
*
* @return
*/
private CommunityTarget createTarget() {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(community));
target.setAddress(new UdpAddress(address));
target.setVersion(SnmpConstants.version2c);
target.setRetries(2);
target.setTimeout(1500);
return target;
}
private String getSnmpValue(String oid, CommunityTarget target) throws IOException {
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(oid)));
pdu.setType(PDU.GET);
ResponseEvent response = snmp.send(pdu, target);
if (response != null && response.getResponse() != null) {
return response.getResponse().get(0).getVariable().toString();
}
return "Neznámé";
}
/**
* prevadi ciselne oznaceni typu rozhrani na nazev
* @param type
* @return
*/
private String getInterfaceType(String type) {
switch (type) {
case "1":
return "Jiné";
case "6":
return "Ethernet";
case "7":
return "ISO 8802-3";
case "9":
return "Token Ring";
case "15":
return "FDDI";
case "23":
return "PPP";
case "24":
return "Loopback";
case "28":
return "ATM";
case "32":
return "Frame Relay";
case "37":
return "IP-over-ATM";
case "53":
return "Fibre Channel";
case "62":
return "Fast Ethernet (100 Mbps)";
case "69":
return "Gigabit Ethernet (1 Gbps)";
case "71":
return "WiFi (802.11)";
case "94":
return "ATM Subinterface";
case "117":
return "Gigabit Ethernet (1 Gbps)";
case "131":
return "Tunnel";
case "135":
return "VLAN";
case "136":
return "LACP (Link Aggregation)";
case "161":
return "ISDN";
case "169":
return "DSL";
case "175":
return "DOCSIS (kabelový modem)";
case "181":
return "ATM (PON)";
case "182":
return "Ethernet (PON)";
case "209":
return "Bridge";
case "237":
return "LTE";
case "243":
return "5G";
default:
return "(" + type + ") Neznámé ";
}
}
/**
* prevadi ciselne oznaceni statusu rozhrani na nazev
*
* @param status
* @return
*/
private String getInterfaceStatus(String status) {
switch (status) {
case "1":
return "Up"; // up(1)
case "2":
return "Down"; // down(2)
case "3":
return "Testing"; // testing(3)
case "4":
return "Unknown"; // unknown(4)
case "5":
return "Dormant"; // dormant(5)
case "6":
return "No present"; // notPresent(6)
case "7":
return "Lower Layer Down"; // lowerLayerDown(7)
default:
return "Neznámé (" + status + ")";
}
}
/**
* Pomocná metoda pro rmátování času z Unixového formátu na čitelný
*
* @param unixTimestamp
* @return
*/
private String formatTimestamp(String unixTimestamp) {
try {
long timestamp = Long.parseLong(unixTimestamp);
return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(timestamp * 1000));
} catch (NumberFormatException e) {
return "";
}
}
/**
* funkce převede rychlost do citelnejsi podoby
* @param ifSpeed
* @return
*/
private static String formatIfSpeed(long ifSpeed) {
String[] UNITS = {"bps", "kbps", "Mbps", "Gbps", "Tbps"};
if (ifSpeed <= 0) {
return "-";
}
int unitIndex = 0;
double speed = ifSpeed;
while (speed >= 1000 && unitIndex < UNITS.length - 1) {
speed /= 1000;
unitIndex++;
}
long roundedSpeed = Math.round(speed); // Zaokrouhlení na celé číslo
DecimalFormat df = new DecimalFormat("#,###"); // Oddělování tisíců
return df.format(roundedSpeed) + " " + UNITS[unitIndex];
}
/**
* prevede adm status na text
* @param status
* @return
*/
private static String convertIfAdminStatus(String status) {
return switch (status) {
case "1" -> "Up";
case "2" -> "Down";
case "3" -> "Testing";
default -> "Unknown";
};
}
}

View File

@ -0,0 +1,57 @@
package jnet.lib.snmp;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.*;
public class SNMPTester {
private String address;
private String community;
private int version;
public SNMPTester(String address, String port, String community, int version) {
this.address = address+"/"+port;
this.community = community;
this.version = version;
}
public boolean testSnmp() {
try {
// Nastavení SNMP agenta
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// Cílový hostitel a community string
Target target = new CommunityTarget();
((CommunityTarget) target).setCommunity(new OctetString(this.community));
target.setVersion(this.version);
target.setAddress(new UdpAddress(this.address));
target.setRetries(3); // Počet pokusů
target.setTimeout(5000); // Timeout v milisekundách
// Odeslání SNMP požadavku na systémovou OID (sysDescr)
PDU request = new PDU();
request.add(new VariableBinding(SnmpConstants.sysDescr)); // OID pro systémový popis
request.setType(PDU.GET);
// Odeslání požadavku
ResponseEvent response = snmp.get(request, target);
snmp.close(); // Ukončení SNMP komunikace
// Zpracování odpovědi
if (response != null && response.getResponse() != null) {
PDU pdu = response.getResponse();
return true; // Funkční SNMP
} else {
return false; // Nefunkční SNMP
}
} catch (Exception e) {
return false; // Chyba komunikace
}
}
}

View File

@ -0,0 +1,136 @@
package jnet.lib.snmp;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.event.ResponseListener;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.snmp4j.CommunityTarget;
public class SNMPTrafficMonitor {
private String address;
private String port;
private String community;
private int version;
private int interfaceIndex;
private final List<TrafficListener> listeners = new ArrayList<>();
private Snmp snmp;
private Timer timer;
private long prevInOctets = -1;
private long prevOutOctets = -1;
private long prevTimestamp = -1;
// OIDy pro SNMP dotaz na traffic
private static final String IF_IN_OCTETS = "1.3.6.1.2.1.2.2.1.10"; // Inbound traffic
private static final String IF_OUT_OCTETS = "1.3.6.1.2.1.2.2.1.16"; // Outbound traffic
public SNMPTrafficMonitor(String targetAddress, String port, String community, int version, int interfaceIndex) {
this.address = targetAddress;
this.port = port;
this.community = community;
this.version = version;
this.interfaceIndex = interfaceIndex;
}
public void addTrafficListener(TrafficListener listener) {
listeners.add(listener);
}
public void startMonitoring(long intervalMs) throws IOException {
TransportMapping<UdpAddress> transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();
timer = new Timer(true);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
queryTraffic();
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, intervalMs);
}
public void stopMonitoring() throws IOException {
if (timer != null) {
timer.cancel();
}
if (snmp != null) {
snmp.close();
}
}
private void queryTraffic() throws IOException {
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(IF_IN_OCTETS + "." + interfaceIndex)));
pdu.add(new VariableBinding(new OID(IF_OUT_OCTETS + "." + interfaceIndex)));
pdu.setType(PDU.GET);
CommunityTarget target = createTarget();
snmp.send(pdu, target, null, new ResponseListener() {
@Override
public void onResponse(ResponseEvent event) {
PDU response = event.getResponse();
if (response != null) {
long inOctets = response.get(0).getVariable().toLong();
long outOctets = response.get(1).getVariable().toLong();
long currentTimestamp = System.currentTimeMillis();
if (prevInOctets != -1 && prevOutOctets != -1) {
double elapsedSeconds = (currentTimestamp - prevTimestamp) / 1000.0;
long inBps = (long) ((inOctets - prevInOctets) / elapsedSeconds);
long outBps = (long) ((outOctets - prevOutOctets) / elapsedSeconds);
// Zavoláme listener s hodnotami v Bps (Byte per Second)
notifyListeners(inBps, outBps);
}
prevInOctets = inOctets;
prevOutOctets = outOctets;
prevTimestamp = currentTimestamp;
}
}
});
}
private void notifyListeners(long inBps, long outBps) {
for (TrafficListener listener : listeners) {
listener.onTrafficUpdate(inBps, outBps);
}
}
/**
* Vytvoření SNMP cíle (target).
*/
private CommunityTarget createTarget() {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(this.community));
target.setAddress(new UdpAddress(this.address+"/"+this.port));
target.setVersion(this.version);
target.setRetries(2);
target.setTimeout(1500);
return target;
}
public interface TrafficListener {
void onTrafficUpdate(long inBps, long outBps);
}
}