linux下获取本机ip代码和判断ip

本文介绍了一种使用C++编程语言获取本地IPv4地址的方法,并提供了两种验证IPv4地址有效性的方案:一种是通过解析字符串的方式进行验证,另一种则是利用系统函数inet_pton进行有效性检查。
#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;
}

 

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值