整数IP地址 - Ç [英] Integer to IP Address - C

查看:156
本文介绍了整数IP地址 - Ç的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个小测验preparing,我有一个强烈的怀疑我可以实现这样一个函数来负责。基本上,鉴于网络符号格式的IP地址,我们怎样才能从一个32位整数到这一个字符串的点分十进制形式(类似于155.247.182.83)...?显然,我们不能使用任何类型的INET函数要么...我难倒!

I'm preparing for a quiz, and I have a strong suspicion I may be tasked with implementing such a function. Basically, given an IP address in network notation, how can we get that from a 32 bit integer into a string in it's dotted decimal notation (something like 155.247.182.83)...? Obviously we can't be using any type of inet functions either...I'm stumped!

推荐答案

下面是一个简单的方法来做到这一点:在(IP>> 8)(IP>> 16)(IP>> 24)移动第二,第三和第四个字节为低位字节,而&安培; 0xFF的在每一步隔离至少显著字节。

Here's a simple method to do it: The (ip >> 8), (ip >> 16) and (ip >> 24) moves the 2nd, 3rd and 4th bytes into the lower order byte, while the & 0xFF isolates the least significant byte at each step.

void print_ip(int ip)
{
    unsigned char bytes[4];
    bytes[0] = ip & 0xFF;
    bytes[1] = (ip >> 8) & 0xFF;
    bytes[2] = (ip >> 16) & 0xFF;
    bytes[3] = (ip >> 24) & 0xFF;	
    printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);        
}

有一个隐含的字节[0] =(IP>> 0)及为0xFF; 在第一步

使用的snprintf()将其打印为一个字符串。

Use snprintf() to print it to a string.

这篇关于整数IP地址 - Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆