ip地址转十六进制

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值