Chinaunix首页 | 论坛 | 博客
  • 博客访问: 663148
  • 博文数量: 111
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 1461
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-08 14:40
文章分类

全部博文(111)

文章存档

2010年(10)

2009年(70)

2008年(31)

我的朋友

分类: C/C++

2009-11-17 20:35:00

获得局域网的机器的MAC地址

//devc++编译,将两个库加载进去

#include
#include
#include
#include
#include


#pragma comment ( lib, "ws2_32.lib" )
#pragma comment ( lib, "Iphlpapi.lib" )

int main( int argc, char * argv[] )
{
int numberOfHost = 1;
struct hostent *remoteHostent;

//处理命令行参数
if ( argc == 3 )
numberOfHost = atoi( argv[2] );
if ( ( argc >3 ) || ( argc < 2 ) )
{
printf( "RmtHost v0.2 - Get remote HostName /MacAddress " );
printf( "by ShotgunLabs ( [email]Shotgun@xici.net[/email] ) " );
printf( "Usage : RmtHost.exe [RemoteIP] " );
printf( "Example: RmtHost.exe 192.168.0.3 " );
printf( " RmtHost.exe 192.168.0.3 2 " );
system("pause");
exit( 0 );
}
//初始化SOCKET
WSADATA wsaData;
int iRet = WSAStartup(MAKEWORD(2,1), &wsaData);
if ( iRet != 0 )
{
printf( "WSAStartup Error:%d ", GetLastError() );
exit( 0 );
}


int nRemoteAddr = inet_addr( argv[1] );
remoteHostent= (struct hostent*)malloc( sizeof(struct hostent ));
struct in_addr sa;
for ( int i = 0; i < numberOfHost; i ++ )
        {
        //获取远程机器名
        sa.s_addr = nRemoteAddr;
        printf( " IpAddress : %s ", inet_ntoa( sa ) );
        remoteHostent = gethostbyaddr( (char*)&nRemoteAddr,4, AF_INET );
        if ( remoteHostent )
                printf( "HostName : %s ",remoteHostent->h_name );
        else
        printf( "gethostbyaddr Error:%d ",GetLastError() );
       
       
        //发送ARP查询包获得远程MAC地址
        unsigned char macAddress[6];
        ULONG macAddLen = 6;
        iRet=SendARP(nRemoteAddr, (unsigned long)NULL,(PULONG)&macAddress, &macAddLen);
        if ( iRet == NO_ERROR )
                {
                printf( "MacAddress: " );
                for( int i =0; i<6; i++ )
                        {
                        printf( "%.2x", macAddress[i] );
                        if ( i<5 ) printf( "-" );
                        }               
                printf( " " );
                }
        else
        printf( "SendARP Error:%d ", GetLastError());

        nRemoteAddr = htonl( ntohl( nRemoteAddr ) + 1 );

        }

阅读(2170) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~