📄 test_ip.cpp
字号:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;
#define MaxIFs 8
int get_ip()
{
int fd;
struct ifconf if_conf; /* net/if.h */
struct sockaddr_in *sin;
struct in_addr test;
inet_aton(sin, test);
fd = socket(PF_INET, SOCK_DGRAM, 0);
if_conf.ifc_req = (struct ifreq *)malloc(MaxIFs * sizeof(struct ifreq));
if_conf.ifc_len = MaxIFs * sizeof(struct ifreq);
if(ioctl(fd, SIOCGIFCONF, &if_conf) == -1)
{
perror("ioctl");
close(fd);
return 1;
}
close(fd);
printf("all network interfaces\n");
for (unsigned int i = 0; i < if_conf.ifc_len / sizeof(struct ifreq); i++)
{
sin = (struct sockaddr_in *)&if_conf.ifc_req[i].ifr_addr;
{
char buf[64];
const char *p;
p = inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
if (p == NULL)
{
perror("inet_ntop");
exit(1);
}
else
{
printf("%8s", if_conf.ifc_req[i].ifr_name);
printf(": %s\n", p);
}
}
}
free(if_conf.ifc_req);
return 0;
}
bool check_ipaddr(const char *szIPAddr)
{
struct in_addr inp;
if ( !inet_aton(szIPAddr, &inp) )
{
cout << "The format of IP address :" << szIPAddr << " is mistaken." <<endl;
return false;
}
unsigned long ulIP = ntohl(inp.s_addr);
//printf("ulIP = %x\n",ulIP);
//1.0.0.0 ⅹ 16777216 (01000000)
//126.255.255.255 ⅹ 2130706431 (7EFFFFFF)
//128.0.0.0 ⅹ 2147483648 (80000000)
//191.255.255.255 ⅹ 3221225471 (BFFFFFFF)
//192.0.0.0 ⅹ 3221225472 (C0000000)
//223.255.255.255 ⅹ 3758096383 (DFFFFFFF)
if((ulIP <= 0x01000000) ||
(ulIP >= 0x7EFFFFFF && ulIP <= 0x80000000) ||
(ulIP >= 0xBFFFFFFF && ulIP <= 0xC0000000) ||
(ulIP >= 0xDFFFFFFF))
{
cout << "IP address :" << szIPAddr << " which cannot be set is set." <<endl;
return false;
}
cout << "IP address :" << szIPAddr << " is a validate IP." <<endl;
return true;
}
int test_ip()
{
check_ipaddr("10.0.0.1");
check_ipaddr("127.0.0.1");
check_ipaddr("1.0.0.0");
check_ipaddr("126.255.255.255");
check_ipaddr("191.255.255.255");
check_ipaddr("223.255.255.255");
check_ipaddr("255.255.255.255");
get_ip();
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -