参考:

C++中inet_pton、inet_ntop函数_Promising丶的博客-CSDN博客_c++ inet_ntop

‘inet_pton’ was not declared in this scope_无名_四叶草的博客-CSDN博客

linux下使用g++编译cpp工程 - BattleScars - 博客园

查看当前系统的字节序 - 长虹落日 - 博客园

“字节序”是个什么鬼? - 知乎

linux编译, 代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main (void)
{
	char IPdotdec[20]; //存放点分十进制IP地址
	struct in_addr s; // IPv4地址结构体
	// 输入IP地址
	printf("Please input IP address: ");
	scanf("%s", IPdotdec);
	// 转换
	inet_pton(AF_INET, IPdotdec, (void *)&s);
	printf("inet_pton: 0x%x\n", s.s_addr); // 注意得到的字节序
	// 反转换
	inet_ntop(AF_INET, (void *)&s, IPdotdec, 16);
	printf("inet_ntop: %s\n", IPdotdec);
}

执行结果:

[linux@ ip_address]$g++ main.cpp
[linux@ ip_address]$
[linux@ ip_address]$./a.out
Please input IP address: 1.1.1.1
inet_pton: 0x1010101
inet_ntop: 1.1.1.1
[linux@ ip_address]$./a.out
Please input IP address: 192.168.1.1
inet_pton: 0x101a8c0
inet_ntop: 192.168.1.1
[linux@ ip_address]$./a.out
Please input IP address: 2.2.2.2
inet_pton: 0x2020202
inet_ntop: 2.2.2.2

增加字节序判断:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int isLittleEndian()
{
    unsigned short i=1;
    return (1 == *((char *)&i));
}
int printSystemEndian() 
{
    if(isLittleEndian())
    {
        printf("Low byte order\n");//低字节序
    }
    else
    {
        printf("High byte order\n");//高字节序
    }
}
int main (void)
{
	char IPdotdec[20]; //存放点分十进制IP地址
	struct in_addr s; // IPv4地址结构体
	// 输入IP地址
	printf("Please input IP address: ");
	scanf("%s", IPdotdec);
	// 转换
	inet_pton(AF_INET, IPdotdec, (void *)&s);
	printf("inet_pton: 0x%x\n", s.s_addr); // 注意得到的字节序
	// 反转换
	inet_ntop(AF_INET, (void *)&s, IPdotdec, 16);
	printf("inet_ntop: %s\n", IPdotdec);
    
    printSystemEndian();
}

执行结果:

[linux@ ip_address]$g++ main.cpp -o main
[linux@ ip_address]$
[linux@ ip_address]$./main
Please input IP address: 192.168.1.1
inet_pton: 0x101a8c0
inet_ntop: 192.168.1.1
Low byte order

Logo

更多推荐