Common Get Web Client Mac Address Method (通用获取Web客户端MAC地址方法)

本文介绍了一个Java Applet程序,该程序能够获取并显示计算机的MAC地址。它通过使用Java网络接口API来检索MAC地址,并提供了多种格式化输出选项。此外,还提供了一个客户端示例,展示了如何在网页中嵌入此Applet并调用其方法。
参考:http://techdetails.agwego.com/2008/02/11/37/
实现:Java Applet
优点:兼容所有支持Applet的浏览器.
Applet 源码:

/*
* Author: Tim Desjardins
* Copyright (c) 2008 Agwego Enterprises Inc.
*
* Feel free to use or abuse this code anyway you wish, without warranty of course.
*/

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.ArrayList;
import java.applet.Applet;

public class MacAddressApplet extends Applet
{
public static String sep = ":";
public static String format = "%02X";

/**
* getMacAddress - return the first mac address found
* separator - byte seperator default ":"
* format - byte formatter default "%02X"
*
* @param ni - the network interface
* @return String - the mac address as a string
* @throws SocketException - pass it on
*/
public static String macToString( NetworkInterface ni ) throws SocketException
{
return macToString( ni, MacAddressApplet.sep, MacAddressApplet.format );
}

/**
* getMacAddress - return the first mac address found
*
* @param ni - the network interface
* @param separator - byte seperator default ":"
* @param format - byte formatter default "%02X"
* @return String - the mac address as a string
* @throws SocketException - pass it on
*/
public static String macToString( NetworkInterface ni, String separator, String format ) throws SocketException
{
byte mac [] = ni.getHardwareAddress();

if( mac != null ) {
StringBuffer macAddress = new StringBuffer( "" );
String sep = "";
for( byte o : mac ) {
macAddress.append( sep ).append( String.format( format, o ) );
sep = separator;
}
return macAddress.toString();
}

return null;
}

/**
* getMacAddress - return the first mac address found
*
* @return the mac address or undefined
*/
public static String getMacAddress()
{
try {
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();

// not all interface will have a mac address for instance loopback on windows
while( nis.hasMoreElements() ) {
String mac = macToString( nis.nextElement() );
if( mac != null )
return mac;
}
} catch( SocketException ex ) {
System.err.println( "SocketException:: " + ex.getMessage() );
ex.printStackTrace();
} catch( Exception ex ) {
System.err.println( "Exception:: " + ex.getMessage() );
ex.printStackTrace();
}

return "undefined";
}

/**
* getMacAddressesJSON - return all mac addresses found
*
* @return a JSON array of strings (as a string)
*/
public static String getMacAddressesJSON()
{
try {
String macs [] = getMacAddresses();

String sep = "";
StringBuffer macArray = new StringBuffer( "['" );
for( String mac: macs ) {
macArray.append( sep ).append( mac );
sep = "','";
}
macArray.append( "']" );

return macArray.toString();
} catch( Exception ex ) {
System.err.println( "Exception:: " + ex.getMessage() );
ex.printStackTrace();
}

return "[]";
}

/**
* getMacAddresses - return all mac addresses found
*
* @return array of strings (mac addresses) empty if none found
*/
public static String [] getMacAddresses()
{
try {
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();

ArrayList<String> macs = new ArrayList<String>();
while( nis.hasMoreElements() ) {
String mac = macToString( nis.nextElement() );
// not all interface will have a mac address for instance loopback on windows
if( mac != null ) {
macs.add( mac );
}
}
return macs.toArray( new String[0] );
} catch( SocketException ex ) {
System.err.println( "SocketException:: " + ex.getMessage() );
ex.printStackTrace();
} catch( Exception ex ) {
System.err.println( "Exception:: " + ex.getMessage() );
ex.printStackTrace();
}

return new String[0];
}

/**
* getMacAddresses - return all mac addresses found
*
* @param sep - use a different separator
*/
public static void setSep( String sep )
{
try {
MacAddressApplet.sep = sep;
} catch( Exception ex ) {
// don't care
}
}

/**
* getMacAddresses - return all mac addresses found
*
* @param format - the output format string for bytes that can be overridden default hex.
*/
public static void setFormat( String format )
{
try {
MacAddressApplet.format = format;
} catch( Exception ex ) {
// don't care
}
}

public static void main( String... args )
{
System.err.println( " MacAddress = " + getMacAddress() );

setSep( "-" );
String macs [] = getMacAddresses();

for( String mac : macs )
System.err.println( " MacAddresses = " + mac );

setSep( ":" );
System.err.println( " MacAddresses JSON = " + getMacAddressesJSON() );
}
}


客户端示例代码:

<!--
*
* Author: Tim Desjardins
* Copyright (c) 2008 Agwego Enterprises Inc.
*
* Feel free to use or abuse this code anyway you wish, without warranty of course.
-->
<html>
<head></head>
<body>

<a href="" onclick="macs.getMacAddress();"> Get "first" MAC Address</a>
<br/>
<br/>
<a href="" onclick="macs.getMacAddressesJSON();"> Get all MAC Addresses</a>

<!--[if !IE]> Firefox and others will use outer object -->
<embed type="application/x-java-applet"
name="macaddressapplet"
width="0"
height="0"
code="MacAddressApplet"
archive="macaddressapplet.jar"
pluginspage="http://java.sun.com/javase/downloads/index.jsp"
style="position:absolute; top:-1000px; left:-1000px;">
<noembed>
<!--<![endif]-->
<!---->
<object classid="clsid:CAFEEFAC-0016-0000-FFFF-ABCDEFFEDCBA"
type="application/x-java-applet"
name="macaddressapplet"
style="position:absolute; top:-1000px; left:-1000px;"
>
<param name="code" value="MacAddressApplet">
<param name="archive" value="macaddressapplet.jar" >
<param name="mayscript" value="true">
<param name="scriptable" value="true">
<param name="width" value="0">
<param name="height" value="0">
</object>
<!--[if !IE]> Firefox and others will use outer object -->
</noembed>
</embed>
<!--<![endif]-->

<script type="text/javascript">
var macs = {
getMacAddress : function()
{
document.macaddressapplet.setSep( "-" );
alert( "Mac Address = " + document.macaddressapplet.getMacAddress() );
},

getMacAddressesJSON : function()
{
document.macaddressapplet.setSep( ":" );
document.macaddressapplet.setFormat( "%02x" );
var macs = eval( String( document.macaddressapplet.getMacAddressesJSON() ) );
var mac_string = "";
for( var idx = 0; idx < macs.length; idx ++ )
mac_string += "\t" + macs[ idx ] + "\n ";

alert( "Mac Addresses = \n" + mac_string );
}
}
</script>

</body>

</html>
<think>Hmm, the user is asking about implementing a MongoDB database listing function in C, specifically a getDBs() method. Let me analyze this carefully. First, I recall from previous interactions that MongoDB provides a C driver (libmongoc) for database operations. The user seems to be working on a C application that needs to interface with MongoDB. Looking at the references provided earlier, reference [1] mentions MongoDB database tools, while [3] explains MongoDB's document-oriented nature. Reference [2] lists MongoDB features including its query capabilities, which is relevant here. Reference [4] shows backup syntax but isn't directly applicable. The key points I need to address: - There's no direct "getDBs()" function in the C driver - that appears to be a Java/Python convention - In C, we work with mongoc_client_t handles and the mongoc_client_get_database_names_with_opts() function - The user will need to handle memory management carefully with bson_error_t and bson_strfreev() I should emphasize the required steps: 1. Creating a client instance 2. Calling the proper database listing function 3. Error handling 4. Memory cleanup The user might not be aware that MongoDB requires connection strings or that database names need freeing. I should include important notes about: - Including the correct headers - Compiling with libmongoc - The asynchronous nature of the function - Proper error checking Sample code would really help here. I'll structure a complete example showing initialization, execution and cleanup. The bson_error_t handling is particularly important since C doesn't have exceptions. For related questions, I should cover: - How to get collection names (natural extension) - Connection pooling (for production use) - How to handle authentication (common follow-up) - Alternatives to listing all databases (partial listing) The user seems technical but may be new to MongoDB's C driver. I'll keep explanations clear but assume C proficiency. The response should balance completeness with readability. </think>根据MongoDB C驱动(libmongoc)的官方规范,查看所有数据库需使用`mongoc_client_get_database_names_with_opts()`函数。以下是完整实现步骤及代码示例: --- ### **C语言实现getDBs()方法** ```c #include <mongoc/mongoc.h> #include <stdio.h> char** getDBs(mongoc_client_t* client) { bson_error_t error; char** db_list = mongoc_client_get_database_names_with_opts( client, // MongoDB客户端实例 NULL, // 查询选项(可为NULL) &error // 错误存储对象 ); if (!db_list) { fprintf(stderr, "获取数据库失败: %s\n", error.message); return NULL; } return db_list; } int main() { // 初始化MongoDB驱动 mongoc_init(); // 创建客户端连接 mongoc_client_t* client = mongoc_client_new("mongodb://localhost:27017"); // 调用函数获取数据库列表 char** databases = getDBs(client); // 打印结果 if (databases) { printf("数据库列表:\n"); for (int i = 0; databases[i]; i++) { printf("- %s\n", databases[i]); } // 释放内存 bson_strfreev(databases); } // 清理资源 mongoc_client_destroy(client); mongoc_cleanup(); return 0; } ``` --- ### **关键说明** 1. **依赖库要求**: - 需安装[MongoDB C驱动](https://github.com/mongodb/mongo-c-driver)(libmongoc) - 编译命令示例:`gcc -o getdbs getdbs.c $(pkg-config --cflags --libs libmongoc-1.0)` 2. **函数特性**: - 返回`char**`类型指针数组,以`NULL`结尾 - 必须用`bson_strfreev()`释放内存[^2] - 支持连接选项(如认证): ```c bson_t opts = BSON_INITIALIZER; BSON_APPEND_UTF8(&opts, "username", "admin"); BSON_APPEND_UTF8(&opts, "password", "pass123"); ``` 3. **替代方案**: ```c mongoc_cursor_t* cursor = mongoc_client_find_databases_with_opts(client, NULL); const bson_t* doc; while (mongoc_cursor_next(cursor, &doc)) { bson_iter_t iter; if (bson_iter_init_find(&iter, doc, "name")) { printf("DB: %s\n", bson_iter_utf8(&iter, NULL)); } } ``` --- ### **常见问题解决** - **连接认证失败**:在连接字符串中添加凭证 `mongodb://admin:pass123@localhost:27017` - **空列表返回**:检查用户权限,需`listDatabases`操作权限[^4] - **内存泄漏**:务必调用`bson_strfreev()`释放返回的数组 --- ### **扩展应用场景** 1. **数据库健康检查**:定期调用验证服务状态 2. **自动化部署**:校验新数据库是否创建成功 3. **多租户系统**:动态获取租户数据库列表 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值