开发者

calculating subnet mask?

how can i calculate the subnet mask having 开发者_JAVA技巧ip address 128.2.19.4 and belong to the subnet 128.2.19.0/25.please give me the detail procedure.i want to learn to calculate.


Here's the algorithm with your example:

The subnet mask is just a representation of the "/25" part of your subnet address.

In IPv4, addresses are 32 bits long, the first 25 bits of which are ones:

1111 1111 1111 1111 1111 1111 1000 0000  

addresses are given in octets -- 8 bits each:

octet 1  .    octet 2  .    octet 3  .    octet 4
0000 0000     0000 0000     0000 0000     0000 0000 
1111 1111     1111 1111     1111 1111     1000 0000

So a decimal representation of each octet is:

255      .    255      .    255      .    128       

That means that your subnet mask would be:

255.255.255.128


The subnet mask is a bitmask. 25 means that 25 out of 32 bits (starting from the top) is used for the network, and the rest for the hosts.

In bytes:    128.2.19.0
In binary    10000000 00000010 00010011 00000000
The bitmask: 11111111 11111111 11111111 10000000
Ergo:        ------- network ------------  host

The last 7 bits are used for hosts. The bitmask as bytes is 255.255.255.128.


Here's how you can do it in C:

#include <stdio.h>
#include <arpa/inet.h>

uint32_t cidr_to_netmask(uint8_t cidr)
{
  uint8_t unset_bits = 32 - cidr;
  return ntohl(0xffffffff << unset_bits);
}

int main(void)
{
    uint8_t cidr = 25;

    uint32_t _netmask = cidr_to_netmask(cidr);
    struct in_addr _netmask_addr = { _netmask };

    char netmask[16];
    if (inet_ntop(AF_INET, (struct in_addr *)&_netmask_addr, (char *)&netmask, sizeof(netmask)) == NULL) { 
      fprintf(stderr, "error.\n"); 
      return 1; 
    }

    printf("%d = %s\n", cidr, netmask);

    return 0;
}

Output:

25 = 255.255.255.128
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜