Lab在局域網中找到你的樹莓派(windows平臺)

如果,你的電腦和樹莓派連在了同一個局域網中。如何從它的MAC地址知道它的IP呢?

教程目標:

寫一個PC的程序,Unix或Windows,能通過對局域網內所有IP地址的ping,找到arp表裏的MAC地址和IP地址對應關 系,根據RPi的MAC段找到局域網內的RPi的IP地址。

教程器材及軟件:

  1. 樹莓派的板子。
  2. SD卡(已經有鏡像刷入)。
  3. 電源線及USB充電器。
  4. putty和psftp。(可以到http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html下載)
  5. 有DHCP的網線。

原理:

原理其實比較簡單,就是arp表和ping的原理。在http://blog.163.com/woxiangxin5@126/blog/static/210450682008102234334173/ 中有比較好的介紹,在此就不重複了。

代碼:

  1. 代碼也十分簡單,就是先從命令行參數中讀入,主機IP地址和樹莓派的MAC地址。(主機IP可以用ipcofig命令查看,樹莓派MAC地址可以用ifconfig在樹莓派中查看。)
  2. 將主機所在的網段全部ping一遍。(此時使用的system()函數,在stdlib.h中。)
  3. 然後,再用arp -a 讀出arp表,用樹莓派的MAC地址找出樹莓派IP地址。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>

void help(void);
void ping_all_ip(const char* local_host_address);
void resolve_arp_tables(char* mac_address,char* ip_address);

int main(int argc,char** argv)
{
	char ip_address[20];
	if(argc!=3)
	{
		help();
		return -1;
	}

	ping_all_ip(argv[1]);
	resolve_arp_tables(argv[2],ip_address);

	puts("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
	printf("Your raspberry's IP is %s\n",ip_address);
	puts("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");


	return 0;
	
}
void help(void)
{
	puts("find_your_raspberry is used to find your raspberry in the"
		"local network.You should run it like find_your_raspberry "
		"(local computer IP in the LAN) (The MAC of your raspberry).");
}
void ping_all_ip(const char* local_host_address)
{
	char address[256];
	char num[10];
	char*p = NULL;
	strcpy(address,local_host_address);
	assert((p=strstr(address,"."))!=NULL);
	p++;
	assert((p=strstr(p,"."))!=NULL);
	p++;
	assert((p=strstr(p,"."))!=NULL);
	p++;
	*p='\0';
	
	//for(int i=100;i<110;i++)
	for(int i=0;i<256;i++)
	{
		char command[512]="ping -n 1 -w 20 ";
		itoa(i,num,10);
		strcat(address,num);
		strcat(command,address);

		puts(command);
		system(command);

		*p='\0';
	}

}
char* strip(char* str)
{
	while(*str==' ' && *str!='\0')
	{
		str++;
	}
	int len = strlen(str);
	while(str[len-1]==' ')
	{
		len--;
		str[len]='\0';
	}
	return str;
}
void resolve_arp_tables(char* mac_address,char* ip_address)
{
	char line[256];
	FILE *file=NULL;

	ip_address[0] = '\0';

	system("arp -a>>temp");
	assert((file=fopen("temp","r"))!=NULL);
	while(!feof(file))
	{
		char* p=NULL;
		fgets(line,sizeof(line),file);
		p=strstr(line,mac_address);
		if(p!=NULL)
		{
			*p='\0';
			strcpy(ip_address,strip(line));
			break;
		}
	}
	fclose(file);

	system("del temp");
}

步驟:

  1. 將樹莓派組裝好後,接上電源。
  2. 查看主機IP地址。

  3. 查看樹莓派的MAC地址。

  4. 編寫代碼。
  5. 編譯執行。
  6. 結果:

備註:

此教程爲浙江大學計算機學院嵌入式系統的擴展實驗報告。

發佈了35 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章