1. 程式人生 > >網路第二課(1)

網路第二課(1)

大笑哈哈。今天學習了一些,host位元組序與network位元組序,之間的轉換。

在計算機的世界裡,我們常用的X86的都是小端的。

而在網路的世界裡,都有是大端的格式。

inet_addr: 

The  inet_addr()  function  converts the Internet
host address cp from IPv4 numbers-and-dots  notation 

 into binary data in network byte order.

原型:

 in_addr_t inet_addr(const char *cp);

  1 #include <stdio.h>
  2 #include <sys/socket.h>
  3 #include <sys/types.h>
  4 #include <arpa/inet.h>
  7 int main()
  8 {
 10         in_addr_t aa;
 12         aa = inet_addr("127.0.0.1");
 13         printf("%x\n",aa);
 14         return 0;
 15 }

自已寫的inet_addr:

 #include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{

int  ret;

char *p = "127.73.23.1";

ret = my_inet_addr(p);

printf("%x\n",ret);

return 0;

}
int  my_inet_addr(const char *cp)
{

int zhi=0,i=0;

char tt[20]={0};

char *a,*b,*c,*d;

char aa,bb,cc,dd;

while(*cp != '\0')

{

printf("%c\n",*cp);

tt[i] = *cp ;

i++;

cp++;

}

char *tmp = tt;

a = tmp;

while(*tmp != '.')

tmp++;

*tmp = '\0';

aa = atoi(a);//將字元,轉換成整數。

b = tmp+1;

while(*tmp != '.')

tmp++;

*tmp = '\0';

bb = atoi(b);

c = tmp+1;

while(*tmp != '.')

tmp++;

*tmp = '\0';

cc = atoi(c);

d = tmp+1;

dd = atoi(d);

zhi = aa+(bb<<8)+(cc<<16)+(dd<<24);

return zhi;


}

自已寫的inet_ntoa:

原型:char *inet_ntoa(struct in_addr in);

The inet_ntoa() function  converts  the  Internet
       host  address in, given in network byte order, to
       a string in IPv4  dotted-decimal  notation.

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

struct my_in_addr{
int aa;
};
char  *my_inet_ntoa(struct my_in_addr shu);
int main()
{


char *cp;

struct my_in_addr shu;

shu.aa = 0x100007f;

my_inet_ntoa(shu);

//printf("%s\n",cp);

return 0;

}
char  *my_inet_ntoa(struct my_in_addr shu)
{

char *a,*b,*c,*d;

char *buff = malloc(sizeof(20));

memset(buff,0,20);

a = (char *)&shu.aa;

b = a+1;

c = b+1;

d = c+1;

sprintf(buff,"%d.%d.%d.%d\n",*a,*b,*c,*d);

printf("%s\n",buff);

return buff;

}