字节转换函数 htonl*的由来与函数定义...
字节转换字符由来:
在网络上面有着许多类型的机器,这些机器在表示数据的字节顺序是不同的, 比如i386芯片是低字节在内存地址的低端,
intel处理器将32位的整数分4个连续的字节,并以字节序1-2-3-4存储到内存中,1表示最高位字节;
而alpha芯片却相反. 为4-3-2-1方式,如果保存整数内存只是以逐个字节的方式来复制,2台不同处理器的计算机得到的整数值不一样,
为了统一,字节转换函数出现了;
函数定义如下:
unsigned long int htonl(unsigned long int hostlong)
unsigned short int htons(unisgned short int hostshort)
unsigned long int ntohl(unsigned long int netlong)
unsigned short int ntohs(unsigned short int netshort)
1. “htonl”是英文“host to network long”缩写,意思为:长整数从主机字节序到网络字节序的转换;
2. 在这四个转换函数中,h 代表host, n 代表 network.s 代表short l 代表long ;
3. htonl(INADDR_ANY)表示允许到达服务器任一网络接口的连接;
附件I:如下不建议使用此方式填充:
server.c代码:
1 /* Make the necessary includes and set up the variables. */ 2 3 #include <sys/types.h> 4 #include <sys/socket.h> 5 #include <stdio.h> 6 #include <netinet/in.h> 7 #include <arpa/inet.h> 8 #include <unistd.h> 9 #include <stdlib.h> 10 11 int main() 12 { 13 int server_sockfd, client_sockfd; 14 int server_len, client_len; 15 struct sockaddr_in server_address; 16 struct sockaddr_in client_address; 17 18 /* Create an unnamed socket for the server. */ 19 20 server_sockfd = socket(AF_INET, SOCK_STREAM, 0); 21 22 /* Name the socket. */ 23 24 server_address.sin_family = AF_INET; 25 server_address.sin_addr.s_addr = inet_addr("127.0.0.1"); 26 server_address.sin_port = 40000; 27 server_len = sizeof(server_address); 28 bind(server_sockfd, (struct sockaddr *)&server_address, server_len); 29 30 /* Create a connection queue and wait for clients. */ 31 32 listen(server_sockfd, 5); 33 while(1) { 34 char ch; 35 36 printf("server waiting\n"); 37 38 /* Accept a connection. */ 39 40 client_len = sizeof(client_address); 41 client_sockfd = accept(server_sockfd, 42 (struct sockaddr *)&client_address, &client_len); 43 44 /* We can now read/write to client on client_sockfd. */ 45 46 read(client_sockfd, &ch, 1); 47 ch++; 48 write(client_sockfd, &ch, 1); 49 close(client_sockfd); 50 } 51 }
client.c代码:
1 /* Make the necessary includes and set up the variables. */ 2 3 #include <sys/types.h> 4 #include <sys/socket.h> 5 #include <stdio.h> 6 #include <netinet/in.h> 7 #include <arpa/inet.h> 8 #include <unistd.h> 9 #include <stdlib.h> 10 11 int main() 12 { 13 int sockfd; 14 int len; 15 struct sockaddr_in address; 16 int result; 17 char ch = 'A'; 18 19 /* Create a socket for the client. */ 20 21 sockfd = socket(AF_INET, SOCK_STREAM, 0); 22 23 /* Name the socket, as agreed with the server. */ 24 25 address.sin_family = AF_INET; 26 address.sin_addr.s_addr = inet_addr("127.0.0.1"); 27 address.sin_port = 40000; 28 len = sizeof(address); 29 30 /* Now connect our socket to the server's socket. */ 31 32 result = connect(sockfd, (struct sockaddr *)&address, len); 33 34 if(result == -1) { 35 perror("oops: client2"); 36 exit(1); 37 } 38 39 /* We can now read/write via sockfd. */ 40 41 write(sockfd, &ch, 1); 42 read(sockfd, &ch, 1); 43 printf("char from server = %c\n", ch); 44 close(sockfd); 45 exit(0); 46 }
运行与问题: