0

I'm trying to write a function that turns 192.168.0.1-255 into an array of IP Addresses. I have this so far (note that there is some more code before this):

typedef struct{
  char addr[17];
} ipv4_address;


typedef struct ipv4_addr_block{
  ipv4_address * addrs;
  unsigned int len;
} ipv4_addr_block;

void get_ipv4_range(const char * r_str, ipv4_addr_block * addr_block )
{
  unsigned int start, end;
  
  char ip_str[strlen(r_str)];
  char temp_last_octet[strlen(r_str)];
  char last_octet[strlen(r_str)];
  strcpy(ip_str, r_str);

  unsigned int split_loc = strloc(ip_str, '-');
  unsigned int last_octet_loc = r_strloc(ip_str,'.');
  strncpy(temp_last_octet, ip_str + r_strloc(ip_str,'.') + 1, split_loc - r_strloc(ip_str,'.') - 1) ;
  
  end = atoi(ip_str + split_loc + 1);
  start = atoi(temp_last_octet);

  if((end == 0 || end > 255) || (start == 0 || start > 255 || start > end)) return;
  
  strncpy(last_octet, ip_str, last_octet_loc + 1);
  last_octet[last_octet_loc + 1] = '\0';
// here start would be 1 and end would be 255
// last_octet(needs a new name) would be 192.168.0.
// By now the addr_block has been allocated but none of it's members have
for(int i = start; i < end + 1; i++)
  {
    printf("%p\n",addr_block->addrs);
    if(!addr_block->addrs){
      addr_block->addrs = (ipv4_address *)malloc(sizeof(ipv4_address));
    }
    else{

      addr_block->addrs = (ipv4_address *)realloc(addr_block->addrs, sizeof(ipv4_address *));
    }

    ipv4_address * current = &addr_block->addrs[addr_block->len];
    snprintf(current->addr, 17, "%s%d",last_octet,i);
    addr_block->len++;

  }

When I remove the snprintf statement, it goes through and allocates memory just fine, but it crashes when I add it back or replace it with functions such as strcpy or memcpy.

What am I doing wrong?

  • `char ip_str[strlen(r_str)]` should be `char ip_str[strlen(r_str)+1]` to allow room for the null terminator. – Barmar Sep 22 '22 at 00:09

0 Answers0