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

   在进行网络编程时,有时侯需要扫描给定网段的所有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
           
函数源码

/* 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 ; }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值