Hola grupo, soy nuevo en java y estoy probando un applet para intentar obtener el IP y MAC Address de la máquina cliente donde se ejecute mi applet, la idea es comparar esa información para en base a esto permitir o denegar el acceso a ciertas funcionalidades de un sistema.
La parte que está comentada
/*---
prueba = this.getMacAddress();
----*/
es la que no puedo ejecutar.
Si alguno de ustedes puede darme una idea se lo agradeceria mucho
El código que estoy probando es el siguiente:
import java.net.InetAddress;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.StringTokenizer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import oracle.jdeveloper.layout.*;
import java.applet.*;
import java.applet.Applet;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* Applet
*/
//public class KSNetworkInfo_Applet extends JApplet {
public class KSNetworkInfo_Applet extends Applet implements ActionListener {
boolean isStandalone = false;
boolean DEBUG = false;
InetAddress address;
TextField portField;
Label display;
DatagramSocket socket;
String param0;
String identificador;
GridBagLayout gridBagLayout1 = new GridBagLayout();
public KSNetworkInfo_Applet() {}
/**
* Constructs a new instance.
*/
/**
* getParameter
* @param key
* @param def
* @return java.lang.String
*/
public void init() {
//Initialize networking stuff.
String host = getCodeBase().getHost();
String prueba = "";
try {
address = InetAddress.getByName(host);
} catch (UnknownHostException e) {
System.out.println("Couldn't get Internet address: Unknown host");
// What should we do?
}
try {
socket = new DatagramSocket();
} catch (IOException e) {
System.out.println("Couldn't create new DatagramSocket");
return;
}
//Set up the UI.
GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridBag);
Label l1;
/*
try
{
prueba = this.getMacAddress();
//l1 = new Label("Quote of the Moment: " + getMacAddress(), Label.CENTER);
}
catch(Exception e)
{
System.out.println("Error para obtener MAC Addess");
return;
}
*/
System.out.println("Ojo");
System.out.println(prueba);
// l1 = new Label(prueba, Label.CENTER);
Label lk = new Label("Quote of the Moment: ", Label.CENTER);
c.anchor = GridBagConstraints.SOUTH;
c.gridwidth = GridBagConstraints.REMAINDER;
// gridBag.setConstraints(l1, c);
// add(l1);
gridBag.setConstraints(lk, c);
add(lk);
display = new Label("(no quote received yet)", Label.CENTER);
c.anchor = GridBagConstraints.NORTH;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(display, c);
add(display);
Label l2 = new Label("Enter the port (on host " + host
+ ") to send the request to:",
Label.RIGHT);
c.anchor = GridBagConstraints.SOUTH;
c.gridwidth = 1;
c.weightx = 0.0;
c.weighty = 1.0;
c.fill = GridBagConstraints.NONE;
gridBag.setConstraints(l2, c);
add(l2);
portField = new TextField(6);
gridBag.setConstraints(portField, c);
add(portField);
Button button = new Button("Send");
gridBag.setConstraints(button, c);
add(button);
portField.addActionListener(this);
button.addActionListener(this);
}
public Insets getInsets() {
return new Insets(4,4,5,5);
}
public void paint(Graphics g) {
Dimension d = getSize();
Color bg = getBackground();
g.setColor(bg);
g.draw3DRect(0, 0, d.width - 1, d.height - 1, true);
g.draw3DRect(3, 3, d.width - 7, d.height - 7, false);
}
public void actionPerformed(ActionEvent event) {
int port;
try {
port = Integer.parseInt(portField.getText());
// doIt(port);
} catch (NumberFormatException e) {
//No integer entered. Should warn the user.
}
}
/*
public void paint(Graphics g) {
try{
g.drawString(getMacAddress(), 50, 25);
}
catch( Exception e)
{ }
}
*/
public final static String getMacAddress() throws IOException {
String os = System.getProperty("os.name");
try {
if(os.startsWith("Windows"))
{
return windowsParseMacAddress(windowsRunIpConfigCommand() );
}
else if(os.startsWith("Linux"))
{
return linuxParseMacAddress(linuxRunIfConfigCommand());
}
else
{
throw new IOException("Sistema Operativo desconocido: " + os);
}
}
catch(ParseException ex)
{
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
/*
* Linux stuff
*/
public final static String linuxParseMacAddress(String ipConfigResponse) throws ParseException {
String localHost = null;
try {
localHost = InetAddress.getLocalHost().getHostAddress();
}
catch(java.net.UnknownHostException ex)
{
ex.printStackTrace();
throw new ParseException(ex.getMessage(), 0);
}
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
String lastMacAddress = null;
while(tokenizer.hasMoreTokens())
{
String line = tokenizer.nextToken().trim();
boolean containsLocalHost = line.indexOf(localHost) >= 0;
// see if line contains IP address
if(containsLocalHost && lastMacAddress != null)
{
return lastMacAddress;
}
// see if line contains MAC address
int macAddressPosition = line.indexOf("HWaddr");
if(macAddressPosition <= 0) continue;
String macAddressCandidate = line.substring(macAddressPosition + 6).trim();
if(linuxIsMacAddress(macAddressCandidate))
{
lastMacAddress = macAddressCandidate;
continue;
}
}
ParseException ex = new ParseException
("cannot read MAC address for " + localHost + " from [" + ipConfigResponse + "]", 0);
ex.printStackTrace();
throw ex;
}
public final static boolean linuxIsMacAddress(String macAddressCandidate) {
// TODO: use a smart regular expression
if(macAddressCandidate.length() != 17) return false;
return true;
}
public final static String linuxRunIfConfigCommand() throws IOException {
Process p = Runtime.getRuntime().exec("ifconfig");
InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer= new StringBuffer();
for (;;) {
int c = stdoutStream.read();
if (c == -1) break;
buffer.append((char)c);
}
String outputText = buffer.toString();
stdoutStream.close();
return outputText;
}
/*
* Windows stuff
*/
public final static String windowsParseMacAddress(String ipConfigResponse) throws ParseException {
String localHost = null;
try {
localHost = InetAddress.getLocalHost().getHostAddress();
} catch(java.net.UnknownHostException ex) {
ex.printStackTrace();
throw new ParseException(ex.getMessage(), 0);
}
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
String lastMacAddress = null;
while(tokenizer.hasMoreTokens()) {
String line = tokenizer.nextToken().trim();
// see if line contains IP address
if(line.endsWith(localHost) && lastMacAddress != null) {
return lastMacAddress;
}
// see if line contains MAC address
int macAddressPosition = line.indexOf(":");
if(macAddressPosition <= 0) continue;
String macAddressCandidate = line.substring(macAddressPosition + 1).trim();
if(windowsIsMacAddress(macAddressCandidate)) {
lastMacAddress = macAddressCandidate;
continue;
}
}
ParseException ex = new ParseException("cannot read MAC address from [" + ipConfigResponse + "]", 0);
ex.printStackTrace();
throw ex;
}
public final static boolean windowsIsMacAddress(String macAddressCandidate) {
// TODO: use a smart regular expression
if(macAddressCandidate.length() != 17) return false;
return true;
}
public final static String windowsRunIpConfigCommand() throws IOException {
Process p = Runtime.getRuntime().exec("ipconfig /all");
InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer= new StringBuffer();
for (;;) {
int c = stdoutStream.read();
if (c == -1) break;
buffer.append((char)c);
}
String outputText = buffer.toString();
stdoutStream.close();
return outputText;
}
}