#include <stdio.h> #include "string.h" unsigned long inet_addr(const char *str) { unsigned long num = 0; int i = 1, j = 1; const char *pstr[4] = { NULL }; pstr[0] = strchr(str, ‘.‘); pstr[1] = strchr(pstr[0] + 1, ‘.‘); pstr[2] = strchr(pstr[1] + 1, ‘.‘); pstr[3] = strchr(str, ‘\0‘); for (j = 0; j < 4; j++) { i = 1; if (j == 0) { while (str != pstr[0]) { num += (*--pstr[j] - ‘0‘) * i; i *= 10; } } else { while (*--pstr[j] != ‘.‘) { num += (*pstr[j] - ‘0‘) * i << 8 * j; i *= 10; } } } return num; } int main() { char str[20] = { ‘\0‘ }; while (true) { printf("请输入需要转换的IP地址:"); scanf_s("%s", str, sizeof(str)); unsigned long addr = inet_addr(str); printf("%s 转换后:0x%x\n", str, addr); } return 0; }
innet_addr函数实现(暂无错误校验),网络字节序固定
原文:https://www.cnblogs.com/veis/p/12587248.html