4

我正在用 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...
4

2 回答 2

8

的十进制成员struct sockaddr按网络字节顺序返回。

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

于 2012-11-08T17:13:14.830 回答
1

hints.sin_port = htons( 9090 );之后添加hints.ai_socktype = SOCK_STREAM;

于 2012-11-08T17:12:50.790 回答