A small program which detects if there is any IP conflict with the IP which you are going to set to your system. Before setting, its pinging the new IP and output will be written to a text file. It will read the output text and if there is a string Request Timed out is present, that means, there is no conflict. If there is conflict, it will not have that string. Also, it will not ping to the current system IP. If we pass the current IP, it will just return 2.
int ping(char* ipstr)
{
{
char comp[50];
char msg[50];
char filestr[50];
FILE *fp;
char ac[80];
char *IPAddr;
WSAData wsaData;
WSAStartup(MAKEWORD(1, 1), &wsaData);
gethostname(ac, sizeof(ac));
struct hostent *phe = gethostbyname(ac);
struct in_addr addr;
memcpy(&addr, phe->h_addr_list[0], sizeof(struct in_addr));
IPAddr = (char*)malloc(16);
if(IPAddr != NULL)
{
IPAddr = inet_ntoa(addr); // Getting the current IP Address of the board.
if(strcmp(IPAddr,ipstr) == 0)
{
return 2;
}
else
{
strcpy(comp,ipstr);
sprintf_s(msg,"ping %s -n 1 >ping.txt",comp);
system(msg);
Sleep(50);
fp = fopen("ping.txt","r");
while(!feof(fp))
{
fscanf(fp,"%s",filestr);
if(strcmp(filestr,"Request") == 0)
{
//IP AVAILABLE
fclose(fp);
return 1;
}
else if(strcmp(filestr,"unreachable.") == 0)
{
//Current IP defaulted to Zero
fclose(fp);
return 1;
}
}
//IP CONFLICT
fclose(fp);
}
}
return 0;
}
2 comments:
Pulippist!
Wouldn't it be more useful if the program scans a range of IP addresses to find one that's available, and ideally, sets it?
I don't have much experience in C/C++... But, what header files do we need to use?
Post a Comment