Check is netmask correct

282 Views Asked by At

Hello i have such netmask, f.e. 255.128.0.0, it is correct netmask, i need to check it.

int s; 
struct in_addr ipvalue;
s = inet_pton(AF_INET, argv[1], &ipvalue);

and if i print s i see 33023 witch in binary form is 00000000.00000000.10000000.11111111, but this is not equals to my input netmask, so how i can check is my netmask is correct or not? Now i am cheking it by comparing netmask in decimal form and for (int i = 31; i >=0; i--) sm |= (1 << i); Thank you.

2

There are 2 best solutions below

0
On BEST ANSWER

if i print s i see 33023 witch in binary form is 00000000.00000000.10000000.11111111

Your problem looks like an endianness issue.

Try the following:

int s; 
struct in_addr ipvalue;
s = inet_pton(AF_INET, argv[1], &ipvalue);
s = ntohl(s);

That should fix the byte order issue.

0
On

whatever you have done, it is correct! But inet_pton returns the converted subnetmask in Big endianness form. so you need to convert it to Little endianness. Then you will get your actual subnetmask.

And you should not print s, because the return value of conversion is stored in s. Try to print structure member of ipvalue. struct in_addr contains-

struct in_addr {
unsigned long s_addr;  
};

so while converting from network byte order to host byte order use ipvalue.s_addr!

Try the following code-

    int s,i;
    struct in_addr ipvalue;
    unsigned long num;

    s = inet_pton(AF_INET, argv[1], &ipvalue);

    num=ntohl(ipvalue.s_addr); // converts network to host byte order!

    for(i=31;i>=0;i--){
            if(num&1<<i)
                    printf("1");
            else
                    printf("0");
    }
    printf("\n");