您的位置:首页 > 运维架构 > Linux

linux下c实现得到给定网段的所有IP

2013-05-20 12:15 239 查看
在进行网络编程时,有时侯需要扫描给定网段的所有IP主机,这就需要首先解析出该网段的所有IP以备下面环节使用。实现代码如下:头文件
#ifndef _ARP_ATTACK_H
#define _ARP_ATTACK_H

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>

typedef struct _addr_t {
struct in_addr sin_addr;
struct _addr_t *next;
}addr_t;

/*
** get the ip address from the ip range
** reutrn: a linklist of address
*/
addr_t *get_ip_range (char *low, char *high);

/*
** description: free the linklist
*/
void free_addr (addr_t *head);
#endif
函数源码[/code]
/* translate the ip range to every ip address */

/* must free the return value */

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "arp_attack.h"

#define error_report(MSG) do{ \
fprintf (stderr, "%s: serours error happened\n", MSG); \
exit (EXIT_FAILURE);}while(0)

#define DEBUG 0

static int arr_to_str (int arr[], char *str)
{
int i;
char buf[5] = {'\0'};
for (i = 0; i < 4; i++) {
sprintf (buf, "%d.", arr[i]);
strcat (str, buf);
}
str[strlen(str) - 1] = '\0'; /* delete the last . at the end */

return 0;}

addr_t  *get_ip_range (char *low, char *high)
{
int low_ip_arr[4] = {0}; /* store the ip address arry */
int high_ip_arr[4] = {0}; /* store the high ip address arry */

char *token;
token = strtok (low, "."); /* cut the dotted decimall string */
int i = 0;
do{
low_ip_arr[i++] = atoi (token);
}while ((token = strtok (NULL, ".")) != NULL && i < 4);

/*same as low */
token = strtok (high, "."); /* cut the dotted decimall string */
i = 0;
do{
high_ip_arr[i++] = atoi (token);
}while ((token = strtok (NULL, ".")) != NULL && i < 4);

addr_t *head, *p, *q;
head = malloc (sizeof (addr_t));
if (NULL == head)  {
error_report ("MALLOC");
}
head->next = NULL;
inet_aton (low, &head->sin_addr);
p = head;
char str_addr[16] = {0};

#if DEBUG
printf ("low_ip_arr[3]= %d\nhigh_ip_arr[3] = %d\n", low_ip_arr[3], high_ip_arr[3]);
#endif
while (low_ip_arr[3]++ < high_ip_arr[3]) {
q = malloc (sizeof (addr_t));
q->next = NULL;

memset (str_addr, '\0', 16);
arr_to_str (low_ip_arr, str_addr);
#if DEBUG
printf ("%s\n", str_addr);
#endif

inet_aton (str_addr, &q->sin_addr);
p->next = q;
p = q;
}

return head;
}
void free_addr (addr_t *head)
{
addr_t *p;
do {
p = head;
head = head->next;
free (p);
}while (NULL != head);
}
//test
int main (int argc, char **argv)
{
addr_t *head;
head = get_ip_range (argv[1], argv[2]);
addr_t *p;
for (p = head; p != NULL; p = p->next) {
printf ("%d\n", p->sin_addr);
}
free_addr (head);

return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: