我是套接字編程的新手,我試圖理解htons()
的操作。我已經閱讀了互聯網上的一些教程,例如this和this。但我無法理解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()有什麼瞭解?你讀過這個:http://en.wikipedia.org/wiki/Endianness。 –
根據Linux手冊'htons()'函數將無符號短整數主機從主機字節順序轉換爲網絡字節順序。 – Shushant
我知道大Endianne和小Endianne,但我不知道htons()正確的操作! – User123422