#include <iostream>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <linux/if.h>
using namespace std;
int GetLocalIP(char* outip);
int main()
{
char ip[20];
int ret = GetLocalIP(ip);
cout<<ip<<endl;
}
int GetLocalIP(char* outip)
{
int sockfd;
struct ifconf ifconf;
char buf[512];
struct ifreq *ifreq;
char* ip;
ifconf.ifc_len = 512;
ifconf.ifc_buf = buf;
if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
return -1;
}
ioctl(sockfd, SIOCGIFCONF, &ifconf);
close(sockfd);
ifreq = (struct ifreq*)buf;
for (int i = (ifconf.ifc_len / sizeof(struct ifreq)); i > 0; i--)
{
ip = inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr);
if(strcmp(ip, "127.0.0.1") == 0)
{
ifreq++;
continue;
}
strcpy(outip, ip);
return 0;
}
return -1;
}
判断ipv4是否合法,用sscanf函数判断。
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
bool IsValidIpv4(const char* ip)
{
if(ip == NULL || strlen(ip) == 0)
{
return false;
}
int a,b,c,d;
char tail = 0;
int field=sscanf(ip,"%d.%d.%d.%d%c",&a,&b,&c,&d,&tail);
if(field==4&&(a>=0&&a<=255)&&(b>=0&&b<=255)&&(c>=0&&c<=255)&&(d>=0&&d<=255))
{
return true;
}
return false;
}
int main()
{
char str[32];
while(cin>>str)
{
if(IsValidIpv4(str))
{
printf("%s is valid ip\n",str);
}
else
{
printf("%s is not valid ip\n",str);
}
}
return 0;
}
上面的方法比较复杂,可以用inet_pton这个系统函数来判断是否是ipv4和ipv6,不过这种方法可能比较耗时。
bool IsValidIpv4Address(const std::string& ip) {
struct sockaddr_in sa;
return ::inet_pton(AF_INET, ip.c_str(), &(sa.sin_addr)) == 1;
}
//C++不支持128位int,所以将ipv6分成两部分,高64位和低64位存储
bool IsValidIpv6Address(const std::string& ip) {
struct sockaddr_in6 sa;
if (::inet_pton(AF_INET6, ip.c_str(), &(sa.sin6_addr)) == 1) {
uint64_t high_ip = htonl(sa.sin6_addr.s6_addr32[0]);
high_ip = (high_ip << 32) | htonl(sa.sin6_addr.s6_addr32[1]);
uint64_t low_ip = htonl(sa.sin6_addr.s6_addr32[2]);
low_ip = (low_ip << 32) | htonl(sa.sin6_addr.s6_addr32[3]);
cout << "high_ip:" << high_ip << ", low_ip:" << low_ip << endl;
return true;
}
return false;
}
本文介绍了一种使用C++编程语言获取本地IPv4地址的方法,并提供了两种验证IPv4地址有效性的方案:一种是通过解析字符串的方式进行验证,另一种则是利用系统函数inet_pton进行有效性检查。
3605

被折叠的 条评论
为什么被折叠?



