IP与整数互转,C语言实现
#define PRINT_IP_FORMAT "%u.%u.%u.%u"
#define PRINT_HIP(x)\
((x >> 24) & 0xFF),\
((x >> 16) & 0xFF),\
((x >> 8) & 0xFF),\
((x >> 0) & 0xFF)
/**
* 整数IP装字符串
* @int_ip 输入转换的整数
* @ip_str输出字符串
*/
void GMIntIPToString(int int_ip, char *ip_str) {
sprintf(ip_str, PRINT_IP_FORMAT, PRINT_HIP(int_ip));
}
/**
* IP字符串转整数
* @ip_str 需要装换的IP
* @return 结果
*/
int GMStringToIntIP(const char* ip_str) {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
sscanf(ip_str, "%d.%d.%d.%d", &a, &b, &c, &d);
int ip = 0;
char *p = (char*) &ip;
*p = a;
p++;
*p = b;
p++;
*p = c;
p++;
*p = d;
return t_htonl(ip);
}
IP 与整数互转,JAVA语言实现
/**
* 整数IP装字符串
*
* @int_ip 输入转换的整数
* @ip_str输出字符串
*/
public static long GMStringToIntIP(String ip_str) {
int indx = 0;
int oindx = 0;
StringBuffer sb = new StringBuffer();
while (ip_str.indexOf(".", indx) > 0) {
oindx = indx - 1;
indx = ip_str.indexOf(".", indx);
sb.append(GMTools.uint8ToByteString(Integer.parseInt(ip_str.substring(oindx + 1, indx))));
indx++;
}
sb.append(GMTools.uint8ToByteString(Integer.parseInt(ip_str.substring(indx))));
return t_ntohl(Long.parseLong(sb.toString(), 2));
}
/**
* 整数IP装字符串
*
* @int_ip 输入转换的整数
* @ip_str输出字符串
*/
public static String GMIntIPToString(long int_ip) {
int[] ret = new int[4];
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
ret[i] = (int) ((int_ip >> (8 * (3 - i))) & 0xFF);
sb.append(ret[i]);
if (i < 3) {
sb.append('.');
}
}
return sb.toString();
}
网友评论