IP與整數(shù)互轉(zhuǎn)酬蹋,C語言實(shí)現(xiàn)
#define PRINT_IP_FORMAT "%u.%u.%u.%u"
#define PRINT_HIP(x)\
((x >> 24) & 0xFF),\
((x >> 16) & 0xFF),\
((x >> 8) & 0xFF),\
((x >> 0) & 0xFF)
/**
* 整數(shù)IP裝字符串
* @int_ip 輸入轉(zhuǎn)換的整數(shù)
* @ip_str輸出字符串
*/
void GMIntIPToString(int int_ip, char *ip_str) {
sprintf(ip_str, PRINT_IP_FORMAT, PRINT_HIP(int_ip));
}
/**
* IP字符串轉(zhuǎn)整數(shù)
* @ip_str 需要裝換的IP
* @return 結(jié)果
*/
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 與整數(shù)互轉(zhuǎn)范抓,JAVA語言實(shí)現(xiàn)
/**
* 整數(shù)IP裝字符串
*
* @int_ip 輸入轉(zhuǎn)換的整數(shù)
* @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));
}
/**
* 整數(shù)IP裝字符串
*
* @int_ip 輸入轉(zhuǎn)換的整數(shù)
* @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();
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者