#include<stdio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h> //strlen
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
char * ip = "192.168.0.1";
unsigned int ipstr2num(char* str)
{
int i = 0;
int j = 0;
char new_str[3];
int num = 0;
char ipstr[15];
unsigned int result[4];
unsigned int ip = 0;
while(*str != '\0')
{
while((*str != '.') && (*str != '\0'))
{
new_str[i] = *str;
num = num * 10 + new_str[i] - '0';
str += 1;
i += 1;
}
result[j] = num;
num = 0;
if (*str == '\0')
{
break;
}
else
{
str += 1;
i = 0;
j += 1;
}
}
ip |= ((result[3]&0xff)<<24);
ip |= ((result[2]&0xff)<<16);
ip |= ((result[1]&0xff)<<8);
ip |= ((result[0]&0xff)<<0);
return ip;
}
int main()
{
int inet;
int ip_data = ipstr2num(ip);
char ntop [16] = "";
printf("ip_data = %x\n",htonl(ip_data)); //大小端转换
inet_pton(AF_INET,ip,&inet);
printf("inet= %x\n",htonl(inet));
inet_ntop(AF_INET,&inet,&ntop,sizeof(ntop));
printf("ntop= %s\n",ntop);
return 0;
}
ip地址转十六进制
于 2022-01-22 17:30:02 首次发布