프로그래밍/C, C++
IP 주소 정수 변환(IP to INT, INT to IP)
즉흥
2014. 7. 3. 18:39
728x90
반응형
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> long long IPtoINT(char *IP_ADDR){ long long ret = 0; char *oct; for (int i = 3; i>=0;i--){ oct = strtok(IP_ADDR, "."); ret += pow(256., i) * atoi(oct); IP_ADDR = NULL; } return ret; } int main(){ char ip_addr[24]; scanf("%s", &ip_addr); printf("%lld",IPtoINT(ip_addr)); return 0; } |
58.184.70.1 이란 IP 주소가 있으면
58 * 256^3
+
184 * 256^2
+
70 * 256^1
+
1 * 256^0
의 계산 결과가 정수형 IP가 됨.
1 2 3 4 5 6 7 8 9 | 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]); } |
728x90
반응형