为什么服务器套接字给出的端口号与绑定端口号不同?

时间:2012-11-08 17:02:21

标签: c sockets network-programming endianness

我在C中编写一个小套接字程序。在服务器端,我使用socket()系统调用创建套接字描述符,然后我将该套接字与端口绑定。在此之后,我试图获取描述符的IP /端口号,它给端口没有区别,然后绑定端口号。我试图使用getsockname()方法返回IP /端口,使用此方法是否正确?请帮帮我。

#define SERVER_ADDR "127.0.0.1"
#define SERVER_PORT "9090" // actual port no I am binding
#define QUEUE_LENGTH 10

int main()
{
struct addrinfo hints, *servinfo, *temp;

memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;

// here I am passing SERVER_PORT == 9090
int status = getaddrinfo(SERVER_ADDR,SERVER_PORT,&hints,&servinfo);
if(status != 0)
{
printf("Server: getaddrinfo() errored with code %d\n",status);
return;
}

int sfd = -1;
for(temp = servinfo; temp != NULL; temp = servinfo->ai_next)
{
sfd = socket(temp->ai_family,temp->ai_socktype,temp->ai_protocol);
if(sfd == -1)
{
  printf("Server: Socket error with code %d\n",sfd);
  continue;
}

status = bind(sfd,temp->ai_addr,temp->ai_addrlen);
if(status == -1)
{
  printf("Server: Bind error with code %d\n",status);
  continue;
}
printf("Server: Bind Successful\n");

// un necessary code goes here
struct sockaddr_in server_address;
char ipv4[INET_ADDRSTRLEN];
int addr_size = sizeof(server_address);
// i am using below method to get the port no from socket descriptor
getsockname(sfd, (struct sockaddr *)&server_address, &addr_size);

// I am expecting below will print 9090. but it prints different port no why ? 
printf("Server Port: %d\n",server_address.sin_port);
printf("Port from getsddrinfo: %d\n",( (struct sockaddr_in *)temp->ai_addr)->sin_port);

inet_ntop(AF_INET, &(server_address.sin_addr),ipv4,INET_ADDRSTRLEN);
printf("Server IP Address: %s\n",ipv4);
// un necessary code ends here
break;
}

if(temp == NULL)
{
printf("Server: Failed to bind\n");
return;
}
status = listen(sfd,QUEUE_LENGTH);
if(status == -1)
{
printf("Server: Listening failed\n");
return;
}
printf("Server: waiting for coneections...\n");

while(1)
{
printf("Server: Main loop, will wait for client to connect...\n");
struct sockaddr client_address;
int addr_length = sizeof client_address;
// accepting client
int new_sfd = accept(sfd,&client_address,&addr_length); 
}
printf("Server: Done!\n"); 
}

输出是:

Server: Bind Successful
Server Port: 33315 --> why this different from one I have binded (9090)
Port from getsddrinfo: 33315 --> why this different from one I have binded (9090)
Server IP Address: 127.0.0.1
Server: waiting for coneections...
Server: Main loop, will wait for client to connect...

2 个答案:

答案 0 :(得分:8)

struct sockaddr的小数成员以网络字节顺序返回。

因此,您需要在使用ntoh系列函数之前将这些值转换为主机字节顺序,然后再打印它们。

答案 1 :(得分:1)

hints.sin_port = htons( 9090 );

之后添加hints.ai_socktype = SOCK_STREAM;