gpt4 book ai didi

c - 如何从接受调用中获取套接字端口号 (C UNIX)

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:12 25 4
gpt4 key购买 nike

我已经完成了一个简单的客户端/服务器程序,其中服务器等待外部连接,如果客户端的端口号在 [1025-2048] 范围内,则返回连接套接字,否则返回 -1。问题是,当我通过客户端地址(应该存储在 sockaddr 结构中)获取端口号时,它告诉我客户端端口号为零,但在客户端程序中我已经将客户端端口号设置为 1999。

服务器

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/signal.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>


int function(int fd_socket) {

int fd_socket_acc;
int len;
int port;
struct sockaddr_in client_addr;

puts("WAITING FOR CLIENT...");

fd_socket_acc = accept(fd_socket, (struct sockaddr*)&client_addr, &len);

puts("CONNECTION DONE.");

port = ntohs (client_addr.sin_port);
printf("client port number: %d \n", port);


if (port >= 1024 && port <= 2048) {

close (fd_socket_acc);
return fd_socket_acc;
}
else {
close(fd_socket_acc);
return -1;
}
}

int main(int argc, char *argv[]) {


int fd_socket;
struct sockaddr_in local_addr;

fd_socket = socket(AF_INET, SOCK_STREAM, 0);

local_addr.sin_family = AF_INET;
local_addr.sin_port = htons(1887);
local_addr.sin_addr.s_addr = INADDR_ANY;

bind(fd_socket, (struct sockaddr*)&local_addr, sizeof(local_addr));

listen(fd_socket, 3);

function(fd_socket);

//close(fd_socket);

}

客户

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/signal.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

int main(int argc, char *argv[]) {

int fd_socket;
struct sockaddr_in local_addr;
struct sockaddr_in server_addr;
struct hostent *hp;

fd_socket = socket(AF_INET, SOCK_STREAM, 0);

local_addr.sin_family = AF_INET;
local_addr.sin_port = htons(1999);
local_addr.sin_addr.s_addr = INADDR_ANY;

bind(fd_socket, (struct sockaddr*)&local_addr, sizeof(local_addr));

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(1887);
//hostname is "ubuntu"
hp = gethostbyname("ubuntu");
bcopy(hp->h_addr, &server_addr.sin_addr, 4);

printf("%d \n", ntohs(local_addr.sin_port));

connect(fd_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));

wait(2);

close(fd_socket);

}

如果我使用 printf("%d", ntohs(local_addr.sin_port)) 在客户端中获取端口号,它会正确标记 1999,但如果我得到服务器中客户端的端口号 printf("%d", ntohs(client_addr.sin_port)) 标记为 0。为什么?

提前致谢!

最佳答案

为了获取client_addr中的客户端端口号通过accept你必须告诉accept通过设置该缓冲区有多大

socklen_t len = sizeof(client_addr);

您也可以通过事后调用来检索它

len = sizeof(client_addr);
getpeername(fd_socket_acc, (struct sockaddr*)&client_addr, &len);

关于c - 如何从接受调用中获取套接字端口号 (C UNIX),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25848922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com