Dopo una "Eternità" che non mi interesso più di java, mi trovo costretto a metter mano ad alcuni programmi fatti molti anni fa e tutt'ora in uso.
Tali applicazioni si connettono, in lan locale, ad un paio di server Postgresql dedicati ad alcune cose e sino a poco fa ben individuati in una lan ad indirizzi statici, se non che è stata ristrutturata la rete ed ora è fuori dal controllo locale ed a indirizzi DHCP, con impossibilità di dedicare degli indirizzi a qualche macchina.
Mi trovo, pertanto, in condizione di dover individuare le macchine in lan locale su cui "possono" risiedere dei server Postgresql e poi, in base alla applicazione in uso, cercare di connettermi al database di interesse.
Da un test veloce, posso farlo con un codice del genere :
Codice: Seleziona tutto
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author ngiuseppe
*/
public class Trovapg {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> schede = NetworkInterface.getNetworkInterfaces();
if (schede != null) {
for (NetworkInterface scheda : Collections.list(schede)) {
cerca_ip_v4(scheda);
}
} else {
System.out.println("Nessuna scheda di rete trovata");
}
} catch (SocketException e) {
e.printStackTrace();
}
for (String ind : ind_ip) {
cerca_5432(ind);
}
}
static void cerca_ip_v4(NetworkInterface scheda) throws SocketException {
if (scheda.getHardwareAddress() != null) {
Enumeration<InetAddress> inetAddresses = scheda.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
if (inetAddress instanceof Inet4Address) {
ind_ip.add(inetAddress.toString().substring(1));
}
}
}
}
static void cerca_5432(String ip) {
String[] elem;
elem = ip.split("\\.");
String base = elem[0] + "." + elem[1] + "." + elem[2] + ".";
System.out.println(base);
System.out.println("Cerco nell'intervallo " + base + "*");
for(int i=1; i<255; i++) {
if (i == 41) {
boolean connesso = connetti(base + "41", 5432);
if (connesso == true) {
System.out.println("Postgresql trovato");
} else {
System.out.println("Nessun server trovato");
}
}
}
}
// funzione per connettersi al server
static boolean connetti(String ip, int port) {
boolean result = false;
try {
Socket s = new Socket(ip, port);
result = true;
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
static ArrayList<String> ind_ip = new ArrayList<>();
}
Qualcuno di Voi ha suggerimenti in merito?
(Preciso che non è proprio possibile riservarsi degli IP)
Grazie per l'attenzione