C指针操作ip地址以4个字节的int类型作为传输对象

//16进制1个和2字符为1个字节,3个支付为2个字节

    int a = 0x12345678;

    char *p = &a;
    printf("%x\n",*p);
    
    p++;//从78移动到56
    printf("%x\n", *p);
    
    p++;//从56移动到34
    printf("%x\n",*p);
void ip2string(int n)
{
    unsigned char *p;
    
    p = &n;
    
    printf("%u.%u.%u.%u\n",*p,*(p+1),*(p+2),*(p+3));
}

void string2ip(char s[])
{
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    sscanf(s,"%d.%d.%d.%d",&a,&b,&c,&d);

    //printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d);

    int ip;

    char *p;
    p = &ip;

    *p = a;
    p++;
    *p = b;
    p++;
    *p = c;
    p++;
    *p = d;


    printf("%d",ip);

}


int main()
{
    //ip地址的保存方法,通过一个int传递IPV4的地址,可以保证4个字节足够了
    //"192.168.1.2" //11个字节
    //"234.213.222.231" //15个字节
    //"1.1.1.1" //7个字节
    //IP在网络中传递的时候是一个DWORD,就是一个int

    //"192.168.6.252"
    int ip = 0;

    unsigned char *p1;
    p1 = &ip;

    *p1 = 192;
    p1++;
    *p1 = 168;
    p1++;
    *p1 = 6;
    p1++;
    *p1 = 252;

    printf("%d\n",ip);

    ip2string(ip);

    char s[100] = "192.168.6.252";

    string2ip(s);




    return 0;
}

 

转载于:https://www.cnblogs.com/jhxk/articles/8442159.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值