C指针操作ip地址以4个字节的int类型作为传输对象
//16进制1个和2字符为1个字节,3个支付为2个字节 int a = 0x12345678; char *p = &a; printf("%x\n",*p); p++;//从78移动到56 printf("%x\n", *p); p++;//从56移动到34 printf("%x\n",*p);
void ip2string(int n) { unsigned char *p; p = &n; printf("%u.%u.%u.%u\n",*p,*(p+1),*(p+2),*(p+3)); } void string2ip(char s[]) { int a = 0; int b = 0; int c = 0; int d = 0; sscanf(s,"%d.%d.%d.%d",&a,&b,&c,&d); //printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d); int ip; char *p; p = &ip; *p = a; p++; *p = b; p++; *p = c; p++; *p = d; printf("%d",ip); } int main() { //ip地址的保存方法,通过一个int传递IPV4的地址,可以保证4个字节足够了 //"192.168.1.2" //11个字节 //"234.213.222.231" //15个字节 //"1.1.1.1" //7个字节 //IP在网络中传递的时候是一个DWORD,就是一个int //"192.168.6.252" int ip = 0; unsigned char *p1; p1 = &ip; *p1 = 192; p1++; *p1 = 168; p1++; *p1 = 6; p1++; *p1 = 252; printf("%d\n",ip); ip2string(ip); char s[100] = "192.168.6.252"; string2ip(s); return 0; }