how to get the IP of the wifi hotspot in Android? - java

As the title says... I'm trying to be able to get the IP of the wifi iface when it is configured as hotspot. Ideally, I would like to find something that works for all the phones.
Of course, the WifiManager is useless when it comes to get info from the AP.
Luckily, I've been able to get the IPs of all the interfaces by doing this:
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
Log.d("IPs", inetAddress.getHostAddress() );
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
This chunk of code will print all the IP of all the interfaces (Wifi hotspot included). The main problem is that I don't find a way to identify the WiFi interface. This is an issue since some phones have multiple interfaces (WiMax, etc). This is what I've tried so far:
Filtering by the wifi iface display name: it's not a good approach because the display name changes from one device to another (wlan0, eth0, wl0.1, etc).
Filtering by its mac address: almost work, but on some devices the hotspot iface does not have a MAC address ( iface.getHardwareAddress() returns null)...so not a valid solution.
Any suggestions?

Here's what I did to get the wifi hotspot ip:
public String getWifiApIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
if (intf.getName().contains("wlan")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& (inetAddress.getAddress().length == 4)) {
Log.d(TAG, inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
This will give you the IP address of any wifi device, which means it's not just for the hotspot. If you're connected to another wifi network (meaning you're not in hotspot mode), it'll return an IP.
You should check if you are in AP mode first or not. You can use this class for that: http://www.whitebyte.info/android/android-wifi-hotspot-manager-class

You can use this.
((WifiManager) mContext.getSystemService(Context.WIFI_SERVICE)).getDhcpInfo().serverAddress
Full Code
private String getHotspotIPAddress() {
int ipAddress = mContext.getSystemService(Context.WIFI_SERVICE)).getDhcpInfo().serverAddress;
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
String ipAddressString;
try {
ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
} catch (UnknownHostException ex) {
ipAddressString = "";
}
return ipAddressString;
}

Here is a possible solution that utilizes WiFiManager ConnectionInfo to find corresponding NetworkInterface.
If you just need the IP then you can use:
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();

When the Wifi is not setup as a hotspot, it has a name android-xx7632x324x32423 home
when hotspot is turned on, that name is gone. Also the ip address changes.
So if you are able to get the Wifi config before enabling the hotspot, first of all you can use intf.getName() to get a reference to it.
Second, the ip changed, so if you know which interface the wifi is in CONNECTED mode, you can use that info to identify it later on after enabling the hotspot.
Below is some code I used for debugging. I just spit out everything I can find, make a huge mess then clean it up when I figured my problem out. GL
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import android.net.ConnectivityManager;
textStatus = (TextView) findViewById(R.id.textStatus);
try {
for (NetworkInterface intf : Collections.list(NetworkInterface.getNetworkInterfaces())) {
for (InetAddress addr : Collections.list(intf.getInetAddresses())) {
if (!addr.isLoopbackAddress()){
textStatus.append("\n\n IP Address: " + addr.getHostAddress() );
textStatus.append("\n" + addr.getHostName() );
textStatus.append("\n" + addr.getCanonicalHostName() );
textStatus.append("\n\n" + intf.toString() );
textStatus.append("\n\n" + intf.getName() );
textStatus.append("\n\n" + intf.isUp() );
}
}
}
} catch (Exception ex) {
textStatus.append("\n\n Error getting IP address: " + ex.getLocalizedMessage() );
}
connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
allInfo = connectivity.getAllNetworkInfo();
mobileInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
textStatus.append("\n\n TypeName: " + mobileInfo.getTypeName());
textStatus.append("\n State: " + mobileInfo.getState());
textStatus.append("\n Subtype: " + mobileInfo.getSubtype());
textStatus.append("\n SubtypeName: " + mobileInfo.getSubtypeName());
textStatus.append("\n Type: " + mobileInfo.getType());
textStatus.append("\n ConnectedOrConnecting: " + mobileInfo.isConnectedOrConnecting());
textStatus.append("\n DetailedState: " + mobileInfo.getDetailedState());
textStatus.append("\n ExtraInfo: " + mobileInfo.getExtraInfo());
textStatus.append("\n Reason: " + mobileInfo.getReason());
textStatus.append("\n Failover: " + mobileInfo.isFailover());
textStatus.append("\n Roaming: " + mobileInfo.isRoaming());
textStatus.append("\n\n 0: " + allInfo[0].toString());
textStatus.append("\n\n 1: " + allInfo[1].toString());
textStatus.append("\n\n 2: " + allInfo[2].toString());

private static byte[] convert2Bytes(int hostAddress) {
byte[] addressBytes = { (byte)(0xff & hostAddress),
(byte)(0xff & (hostAddress >> 8)),
(byte)(0xff & (hostAddress >> 16)),
(byte)(0xff & (hostAddress >> 24)) };
return addressBytes;
}
public static String getApIpAddr(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
byte[] ipAddress = convert2Bytes(dhcpInfo.serverAddress);
try {
String apIpAddr = InetAddress.getByAddress(ipAddress).getHostAddress();
return apIpAddr;
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}

I use the solution of ajma, changing intf.getName().contains("wlan") to intf.getName().contains("wl") || intf.getName().contains("ap"). And it works for many mobile phones.
But it returns null when you just connected to a WiFi.

With the number of new phones coming out every year from new manufacturers simply identifying the name of the wireless interface is bound to fail in the nearest future. The following method can get the remote server ip from the integer ip returned by getDhcpInfo().serverAddress.
public String getIPv4Address(int ipAddress) {
// convert integer ip to a byte array
byte[] tempAddress = BigInteger.valueOf(ipAddress).toByteArray();
int size = tempAddress.length;
// reverse the content of the byte array
for(int i = 0; i < size/2; i++) {
byte temp = tempAddress[size-1-i];
tempAddress[size-1-i] = tempAddress[i];
tempAddress[i] = temp;
}
try {
// get the IPv4 formatted ip from the reversed byte array
InetAddress inetIP = InetAddress.getByAddress(tempAddress);
return inetIP.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "";
}
Then you can use it like this from the activity where you use the WiFi service
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
String serverIp = getIPv4Address(wifi.getDhcpInfo().serverAddress);
Log.v("Server Ip", serverIp);
This should show you the IP of the connected server.
NOTE: ensure you have already created a successful connection to an access point (e.g. hotspot) via WiFi before querying for the server ip. You only need the SSID and preSharedkey (if it's secure) to create a successful connection and not the server ip.

Related

Softlayer - list of servers which are powered on

The following java code lists all the bare metal servers in softlayer for a specific SL account and filters for servers which are powered on (e.g. powerState='on'.
public void listServers(Account.Service service, ApiClient client) throws Exception {
service.withMask().hardware().fullyQualifiedDomainName().primaryIpAddress();
service.withMask().hardware().hardwareStatus();
service.withMask().hardware().id();
Account account = service.getObject();
//
// list of softlayer servers for the client account
//
for (Hardware hardware : account.getHardware()) {
String hostname = hardware.getFullyQualifiedDomainName();
String hardwareStatus = (hardware.getHardwareStatus() == null) ? null : hardware.getHardwareStatus().getStatus();
Long serverId = hardware.getId();
String powerState = null;
if (serverId != null) {
Hardware.Service hardwareService = Hardware.service(client, serverId);
hardwareService.setMask("mask[serverPowerState");
try {
powerState = hardwareService.getServerPowerState();
} catch (Exception ex) {
System.out.println("Error, cannot get powerState, hostname=" + hostname + ", msg=" + ex.getMessage());
}
}
System.out.println("Hostname=" + hostname + ", hwStatus=" + hardwareStatus + ", powerState=" + powerState);
}
}
Code seems to work, but for at least one of the servers, it fails on the call to hardwareService.getServerPowerState()
"Unable to establish IPMI v2 / RMCP+ session".
Any ideas why this is failing ?

How to get all the queues and topics from solace

I want to discover all the destinations from solace (queues and topics)
I tried using MBeanServerConnection and query after names (but I didn't find a proper way to use this) or JNDI lookups Destination dest = (Destination) context.lookup(Dest_name), but I don't have the names of the queues/topics.
I am using solace - jms library.
I am searching for smth like this: (but for solace, not activeMq)
get all Queue from activeMQ
You will need to make use of SEMP over the management interface for this.
Sample commands:
curl -d '<rpc><show><queue><name>*</name></queue></show></rpc>' -u semp_username:semp_password http://your_management_ip:your_management_port/SEMP
curl -d '<rpc><show><topic-endpoint><name>*</name></topic-endpoint></show></rpc>' -u semp_username:semp_password http://your_management_ip:your_management_port/SEMP
Note that I'm using curl for simplicity, but any application can perform HTTP POSTs to execute these commands.
If you are using Java, you can refer to the SempHttpSetRequest sample found within the Solace API samples.
Documentation on SEMP can be found here.
However, the larger question here is why do you need to discover all destinations?
One of the features of the message broker is to decouple the publishers and consumers.
If you need to know if your persistent message is being published to a topic with no consumers, you can make use of the reject-msg-to-sender-on-no-subscription-match setting in the publishing application's client-profile.
This means that the publisher will obtain a negative acknowledgement in the event that it tries to publish a message on a topic that has no matching subscribers.
You can refer to "Handling Guaranteed Messages with No Matches" at https://docs.solace.com/Configuring-and-Managing/Configuring-Client-Profiles.htm for further details.
Here is some source code that might help. With the appliance configured correctly, SEMP is also available over JMS on topic "#SEMP/(router)/SHOW".
/**
* Return the SolTopicInfo for this topic (or all topics if 'topic' is null).
*
* #param session
* #param endpointName
* #return
*/
public static SolTopicInfo[] getTopicInfo(JCSMPSession session, String endpointName, String vpn,
String sempVersion) {
XMLMessageConsumer cons = null;
XMLMessageProducer prod = null;
Map<String, SolTopicInfo> tiMap = new HashMap<String, SolTopicInfo>();
try {
// Create a producer and a consumer, and connect to appliance.
prod = session.getMessageProducer(new PubCallback());
cons = session.getMessageConsumer(new SubCallback());
cons.start();
if (vpn == null) vpn = (String) session.getProperty(JCSMPProperties.VPN_NAME);
if (sempVersion == null) sempVersion = getSempVersion(session);
// Extract the router name.
final String SEMP_SHOW_TE_TOPICS = "<rpc semp-version=\""
+ sempVersion
+ "\"><show><topic-endpoint><name>"
+ endpointName
+ "</name><vpn-name>"+ vpn + "</vpn-name></topic-endpoint></show></rpc>";
RpcReply teTopics = sendRequest(session, SEMP_SHOW_TE_TOPICS);
for (TopicEndpoint2 te : teTopics.getRpc().getShow().getTopicEndpoint().getTopicEndpoints()
.getTopicEndpointArray()) {
SolTopicInfo ti = new SolTopicInfo();
ti.setBindCount(te.getInfo().getBindCount());
//qi.setDescription(qt.getInfo().getNetworkTopic());
ti.setEndpoint(te.getName());
ti.setMessageVPN(te.getInfo().getMessageVpn());
ti.setTopic(te.getInfo().getDestination());
ti.setDurable(te.getInfo().getDurable());
ti.setInSelPres(te.getInfo().getIngressSelectorPresent());
ti.setHwmMB(formatter.format(te.getInfo().getHighWaterMarkInMb()));
ti.setSpoolUsageMB(formatter.format(te.getInfo().getCurrentSpoolUsageInMb()));
ti.setMessagesSpooled(te.getInfo().getNumMessagesSpooled().longValue());
String status = te.getInfo().getIngressConfigStatus().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getEgressConfigStatus().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getIngressSelectorPresent().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getType().substring(0, 1).toUpperCase();
ti.setStatus(status);
tiMap.put(ti.getEndpoint(), ti);
}
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (cons != null)
cons.close();
if (prod != null)
prod.close();
}
return tiMap.values().toArray(new SolTopicInfo[0]);
}
/**
* Return the SolQueueInfo for this queue (or all queues if 'queue' is null).
*
* #param session
* #param queue
* #param vpn (if null, use the session's vpn name)
* #param sempVersion, if null use 'soltr/7_1_1'
* #return
*/
public static SolQueueInfo[] getQueueInfo(JCSMPSession session, String queue, String vpn,
String sempVersion) {
XMLMessageConsumer cons = null;
XMLMessageProducer prod = null;
Map<String, SolQueueInfo> qiMap = new HashMap<String, SolQueueInfo>();
try {
// Create a producer and a consumer, and connect to appliance.
prod = session.getMessageProducer(new PubCallback());
cons = session.getMessageConsumer(new SubCallback());
cons.start();
if (vpn == null) vpn = (String) session.getProperty(JCSMPProperties.VPN_NAME);
if (sempVersion == null) sempVersion = getSempVersion(session);
// Extract the router name.
final String SEMP_SHOW_QUEUE_SUBS = "<rpc semp-version=\""
+ sempVersion
+ "\"><show><queue><name>"
+ queue
+ "</name><vpn-name>"+ vpn + "</vpn-name><subscriptions/><count/><num-elements>200</num-elements></queue></show></rpc>";
RpcReply queueSubs = sendRequest(session, SEMP_SHOW_QUEUE_SUBS);
for (QueueType qt : queueSubs.getRpc().getShow().getQueue().getQueues().getQueueArray()) {
SolQueueInfo qi = new SolQueueInfo();
qi.setBindCount(qt.getInfo().getBindCount());
//qi.setDescription(qt.getInfo().getNetworkTopic());
qi.setName(qt.getName());
qi.setMessageVPN(qt.getInfo().getMessageVpn());
qi.setDurable(qt.getInfo().getDurable());
qi.setEgSelPres(qt.getInfo().getEgressSelectorPresent());
qi.setHwmMB(formatter.format(qt.getInfo().getHighWaterMarkInMb()));
qi.setMessagesSpooled(qt.getInfo().getNumMessagesSpooled().longValue());
qi.setSpoolUsageMB(formatter.format(qt.getInfo().getCurrentSpoolUsageInMb()));
String status = qt.getInfo().getIngressConfigStatus().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getEgressConfigStatus().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getAccessType().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getEgressSelectorPresent().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getType().substring(0, 1).toUpperCase();
status += qt.getInfo().getDurable() ? " D" : " N";
qi.setStatus(status);
for (Subscription sub : qt.getSubscriptions().getSubscriptionArray()) {
qi.addSubscription(sub.getTopic());
}
qiMap.put(qi.getName(), qi);
}
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (cons != null)
cons.close();
if (prod != null)
prod.close();
}
return qiMap.values().toArray(new SolQueueInfo[0]);
}
private static String getSempVersion(JCSMPSession session)
{
String retval = "soltr/7_1_1";
try {
String peerVersion = (String)session.getCapability(CapabilityType.PEER_SOFTWARE_VERSION);
if (peerVersion != null)
{
retval = "soltr/";
String[] version = peerVersion.split("\\.");
retval += version[0];
retval += "_" + version[1];
if (!version[2].equals("0")) retval += "_" + version[2];
}
} catch (Throwable e) {
System.err.println(e);
}
return retval;
}
private static RpcReply sendRequest(JCSMPSession session,
final String requestStr) {
try {
// Set up the requestor and request message.
String routerName = (String) session
.getCapability(CapabilityType.PEER_ROUTER_NAME);
final String SEMP_TOPIC_STRING = String.format("#SEMP/%s/SHOW",
routerName);
final Topic SEMP_TOPIC = JCSMPFactory.onlyInstance().createTopic(
SEMP_TOPIC_STRING);
Requestor requestor = session.createRequestor();
BytesXMLMessage requestMsg = JCSMPFactory.onlyInstance().createMessage(
BytesXMLMessage.class);
requestMsg.writeAttachment(requestStr.getBytes());
BytesXMLMessage replyMsg = requestor
.request(requestMsg, 5000, SEMP_TOPIC);
String replyStr = new String();
if (replyMsg.getAttachmentContentLength() > 0) {
byte[] bytes = new byte[replyMsg.getAttachmentContentLength()];
replyMsg.readAttachmentBytes(bytes);
replyStr = new String(bytes, "US-ASCII");
}
RpcReplyDocument doc = RpcReplyDocument.Factory.parse(replyStr);
RpcReply reply = doc.getRpcReply();
if (reply.isSetPermissionError()) {
throw new RuntimeException(
"Permission Error: Make sure SEMP over message bus SHOW commands are enabled for this VPN");
}
if( reply.isSetParseError() ) {
throw new RuntimeException( "SEMP Parse Error: " + reply.getParseError() );
}
if( reply.isSetLimitError() ) {
throw new RuntimeException( "SEMP Limit Error: " + reply.getLimitError() );
}
if( reply.isSetExecuteResult() && reply.getExecuteResult().isSetReason() ) { // axelp: encountered this error on invalid 'queue' name
throw new RuntimeException( "SEMP Execution Error: " + reply.getExecuteResult().getReason() );
}
return reply;
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (XmlException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
You can get message VPN specific queues and topics using following SEMPv2 command.
curl -s -X GET -u semp_user:semp_pass management_host:management_port/SEMP/v2/monitor/msgVpns/{vpn-name}/queues?select="queueName"
curl -s -X GET -u semp_user:semp_pass management_host:management_port/SEMP/v2/monitor/msgVpns/{vpn-name}/topicEndpoints?select="topicEndpointName"

Find ip address of a device

I can't find the ip address of a device connected to my network. I tried using network interface, but only gives me the loopback address and my pc address; the code that i used is:
try
{
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
System.out.println("Interface: " + e.getName());
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
System.out.println(" " + addr.getHostAddress());
}
}
}catch (Exception e)
{
System.out.println(e.toString());
}
Also, i used PrintServiceLookup,but the methods of that class doesn't give the ip address (the device is a card printer); the code that i used is:
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
System.out.println("Printer Services found:");
printService(services);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
if (service!=null) {
System.out.println("Default Printer Service found:");
System.out.println(service);
}
private static void printService(PrintService[] services) {
if (services!=null && services.length>0) {
for (int i = 0; i < services.length; i++) {
System.out.println(services[i]);
}
}
}
Anyone has a different point of view or perspective to solve the issue?
NetworkInterface.getInetAddresses() is used to return the local IP address of the network adaptor, hence the reason you are seeing loopback and your primary IP.
It's not possible to enumerate devices on the network in this way. You may need to look into something like SNMP.

How to determine which network is used when the device connects to internet

So far I have tried to do this by using RadioInfo class to verify which network is on and check if there are any changes in RadioInfo.getNumberOfPacketsReceived()\Sent(), but this approach is useless if more then one network is on. Can anyone point me in the right direction.
Sorry for the spelling and grammar, English is not my first language.
You need to append your connection type after your URL.
public static String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
connectionString = ";deviceside=true";
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private synchronized static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
Once you writtent this code. use
con = (HttpConnection) Connector.open(url + getConnectionString());
It will determine available network type .

get the common mac addresses on mac os using java

I'm building a java application that gets the mac addresses of a user and compare it with the correspondent value in the database(security feature). but the problem happens on mac os when i discovered that the list of mac addresses has common values(ex: on my mac the list of mac addresses are: 001C42000009,001C42000008,E0F8474267B6(wifi),70CD60F1A5C1(ethernet))
Is there a way to know all these common values that will result when getting the Mac address on Mac os.
Thank you.
At http://standards.ieee.org/develop/regauth/oui/public.html you can lookup a vendor using first 3 bytes of the MAC address, 00-1C-42 points to "Parallels, Inc." (http://www.parallels.com). Are you using some of their virtualization software? Try what java.net.NetworkInterface.isVirtual() returns for this address, if that is not useful then some ugly filter may require (e.g. based on address pattern)
import java.net.NetworkInterface;
import java.util.Enumeration;
public class NetworkInterfaceTest {
public static void main(String args[]) {
try {
Enumeration<NetworkInterface> ie = NetworkInterface.getNetworkInterfaces();
while (ie.hasMoreElements()) {
NetworkInterface i = ie.nextElement();
System.out.println(i.getDisplayName() + " [" + i.getName() + "]: " + formatAddress(i.getHardwareAddress()) + "; isVirtual=" + i.isVirtual());
}
} catch (Exception e){
e.printStackTrace();
}
}
private static String formatAddress(byte[] address) {
if (address == null) {
return null;
}
StringBuilder ret = new StringBuilder(address.length * 2);
for (byte b : address) {
if (ret.length() > 0) {
ret.append('-');
}
String bs = Integer.toHexString(b & 0x000000FF).toUpperCase();
if (bs.length() < 2) {
ret.append('0');
}
ret.append(bs);
}
return ret.toString();
}
}
i believe something like this will do the work for you
try {
InetAddress []addresses = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
/*
* Get NetworkInterfaces for current host and read hardware addresses.
*/
for(int j=0; j< addresses.length; i++) {
System.out.format("%02X%s", mac[i], (i < addresses.length – 1) ? "-" : "");
}
System.out.println();
}
}

Categories