我对socket编程很新,正在尝试理解htons()
的操作。我已经阅读了一些像这个和这个之类的互联网教程。但是我无法准确理解htons()
的作用。我尝试了下面的代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main( int argc, char *argv[] )
{
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
/* First call to socket() function */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
exit(1);
}
/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 5001;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
/* Now bind the host address using bind() call.*/
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
{
perror("ERROR on binding");
exit(1);
}
/* Now start listening for the clients, here process will
* go in sleep mode and will wait for the incoming connection
*/
listen(sockfd,5);
clilen = sizeof(cli_addr);
/* Accept actual connection from the client */
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr,
&clilen);
if (newsockfd < 0)
{
perror("ERROR on accept");
exit(1);
}
/* If connection is established then start communicating */
bzero(buffer,256);
n = read( newsockfd,buffer,255 );
if (n < 0)
{
perror("ERROR reading from socket");
exit(1);
}
printf("Here is the message: %s\n",buffer);
/* Write a response to the client */
n = write(newsockfd,"I got your message",18);
if (n < 0)
{
perror("ERROR writing to socket");
exit(1);
}
return 0;
}
在调试时,sin_port
的值显示为35091
,我不明白为什么portno
从5001
改变为35091
。请问有人能解释一下这种值的变化原因吗?
htons()
函数用于将16位整数从主机字节序转换为网络字节序。主机字节序指的是在特定计算机体系结构中,多字节数据的字节排列顺序;而网络字节序则是一种约定俗成的大端字节序。对于需要在网络上传输数据的应用程序,必须使用htons()
将数据转换为网络字节序以确保数据能够正确地解析。我已经阅读了http://en.wikipedia.org/wiki/Endianness。 - Oliver Charlesworthhtons()
函数将无符号短整型主机字节顺序转换为网络字节顺序。 - Shushantportno
的类型更改为uint16_t
,会发生什么? - jevINADDR_*
常量是本地字节顺序,也必须使用htonl
(而不是htons
)进行网络顺序交换,例如htonl(INADDR_ANY)
。你之所以能够不使用这个操作就成功,是因为INADDR_ANY
恰好是零,它的字节交换结果也是零。如果你使用了INADDR_LOOPBACK
,那么就不会起作用。 - Kaz