最新消息:

C判断IP地址的分类

C/C++ admin 2711浏览 0评论

IP协议中,IP地址被分为5类,即A,B,C,D,E类。其中只有A,B,C类定义了主机的地址。

A类地址中以0开头,网络位为7位,主机位为24位。默认子网掩码为255.0.0.0。

B类地址中以10开头,网络位为14位,主机位为16位。默认子网掩码为255.255.0.0。

C类地址中以110开头,网络位为21位,主机位为8位。默认子网掩码为255.255.255.0。

D类地址中以1110开头,网络位为28位,主机位为0位。默认子网掩码为255.255.255.255。

E类地址中以11110开头,网络位为27位,主机位为0位。默认子网掩码为255.255.255.255。

下面用一个C程序来检验一个IP地址的类别。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* netmask.c:
 * Classify an IP address:
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc,char **argv) {
    int x;               /* Index variable */
    struct sockaddr_in adr_inet;/* AF_INET */
    int len_inet;               /* length  */
    unsigned msb; /* Most significant byte */
    char class;
    char *netmask;
    static struct {
        unsigned char   ip[4];
    } addresses[] = {
        { { 44,135,86,12 } },
        { { 127,0,0,1 } },
        { { 172,16,23,95 } },
        { { 192,168,9,1 } }
    };
    for ( x=0; x<4; ++x ) {
        /*
         * Set up the socket address, to
         * demonstrate how to classify it:
         */
        memset(&adr_inet,0,sizeof adr_inet);
        adr_inet.sin_family = AF_INET;
        adr_inet.sin_port = htons(9000);
        memcpy(&adr_inet.sin_addr.s_addr,
            addresses[x].ip,4);
        len_inet = sizeof adr_inet;
 
        /*
         * Classify this address:
         *
         * 1. Get the Most Significant Byte
         * 2. Classify by that byte
         */
        msb = *(unsigned char *)
            &adr_inet.sin_addr.s_addr;
 
        if ( (msb & 0x80) == 0x00 ) {
            class = 'A';
            netmask = "255.0.0.0";
        } else if ( (msb & 0xC0) == 0x80 ) {
            class = 'B';
            netmask = "255.255.0.0";
        } else if ( (msb & 0xE0) == 0xC0 ) {
            class = 'C';
            netmask = "255.255.255.0";
        } else if ( (msb & 0xF0) == 0xE0 ) {
            class = 'D';
            netmask = "255.255.255.255";
        } else  {
            class = 'E';
            netmask = "255.255.255.255";
        }
 
        printf("Address %u.%u.%u.%u is class %c "
            "netmask %sn",
            addresses[x].ip[0],
            addresses[x].ip[1],
            addresses[x].ip[2],
            addresses[x].ip[3],
            class,
            netmask);
    }
    return 0;
}

其实这个程序很简单,我之所以写到这里是因为存IP的定义对我启发很大:

1
2
3
4
5
6
7
8
    static struct {
        unsigned char   ip[4];
    } addresses[] = {
        { { 44,135,86,12 } },
        { { 127,0,0,1 } },
        { { 172,16,23,95 } },
        { { 192,168,9,1 } }
    };

转载请注明:爱开源 » C判断IP地址的分类

您必须 登录 才能发表评论!