Split IP into host part and network into c

2

I am doing a program in c to divide an IP into the host and network parts, I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(){

struct in_addr addr;
uint8_t *ip={193,110,128,200};
//convierto la IP de uint8_t a uint32_t
uint32_t *ipint = (uint32_t *)ip;
addr.s_addr=ipint;

//empleo las funciones siguientes que devuelven la parte host y la parte red, respectivamente
uint32_t host = inet_lnaof(addr);
uint32_t red = inet_netof(addr);
//convierto el resultado a uint8_t
uint8_t *hostB = (uint8_t *)&host;
uint8_t *redB = (uint8_t *)&red;
//imprimo el resultado
printf("host B: %u.%u.%u.%u\n",hostB[0],hostB[1],hostB[2],hostB[3]);
printf("red B: %u.%u.%u.%u\n",redB[0], redB[1], redB[2], redB[3]);
printf("\n");

}

The problem is that I can not print the correct result. Using the IP of the code as an example, the result is:

 host B: 0.0.0.0
 red B: 0.0.193.0

The 193 is correct, however it does not print the rest of the numbers. What could be the result?

    
asked by kalia 23.09.2017 в 14:21
source

1 answer

3

The code that you sample gives various warnings .

If we solve them, changing ...

uint8_t *ip = {193,110,128,200};

and

addr.s_addr=ipint;

We get a code that compiles without problems ...

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(){

struct in_addr addr;
uint8_t ip[] = {193,110,128,200}; // <- AQUÍ
//convierto la IP de uint8_t a uint32_t
uint32_t *ipint = (uint32_t *)ip;
addr.s_addr=*ipint; // <- AQUÍ

//empleo las funciones siguientes que devuelven la parte host y la parte red, respectivamente
uint32_t host = inet_lnaof(addr);
uint32_t red = inet_netof(addr);
//convierto el resultado a uint8_t
uint8_t *hostB = (uint8_t *)&host;
uint8_t *redB = (uint8_t *)&red;
//imprimo el resultado
printf("host B: %u.%u.%u.%u\n",hostB[0],hostB[1],hostB[2],hostB[3]);
printf("red B: %u.%u.%u.%u\n",redB[0], redB[1], redB[2], redB[3]);
printf("\n");

}

And when executing it, we get the following output:

  

host B: 200.0.0.0
  Network B: 128.110.193.0

    
answered by 23.09.2017 / 14:56
source