ip转整数,可以自己写个函数根据“.”分割,也可以直接用scanf函数。
然后用c语言的移位运算就很简单了。
#include "stdio.h"
#include "string.h"
unsigned int ip_to_uint(char* in_put) {
char* p = in_put;
int len = strlen(p);
char tmp_str[32] = {0};
if (len < 7) {
return 0;
}
int a, b, c, d = 0;
a = atoi(p);
p = strchr(p, '.');
if (p) {
p++;
} else {
return 0;
}
b = atoi(p);
p = strchr(p, '.');
if (p) {
p++;
} else {
return 0;
}
c = atoi(p);
p = strchr(p, '.');
if (p) {
p++;
} else {
return 0;
}
d = atoi(p);
snprintf(tmp_str, sizeof(tmp_str), "%d.%d.%d.%d", a, b, c, d);
if (strcmp(in_put, tmp_str) != 0) {
return 0;
}
return (a << 24 | b << 16 | c << 8 | d);
}
int main(void) {
int i;
int num = 0;
char ip[16] = {0};
char ip_int_str[16] = {0};
int a, b, c, d;
// scanf("%s", ip);
scanf("%d.%d.%d.%d", &a, &b, &c, &d);
scanf("%s", ip_int_str);
// printf("%u\n", ip_to_uint(ip));
printf("%u\n", a << 24 | b << 16 | c << 8 | d);
unsigned int ip_int = strtol(ip_int_str, NULL, 10);
printf("%d.%d.%d.%d", ip_int >> 24 & 0xff, ip_int >> 16 & 0xff,
ip_int >> 8 & 0xff, ip_int & 0xff);
return 0;
}



京公网安备 11010502036488号