我正在用 c 语言创建一个服务器,它可以处理 tcp 连接(供管理员更改服务器配置)和 udp 连接来处理多个客户端
这是我的代码:
struct sockaddr_in si_minhaTCP,si_minhaUDP, si_outra;
int nready, maxfdp1;
int fdTcp;
int fdUdp;
fd_set rset;
if (argc != 4) {
printf("server {client port(udp)} {admin port(tcp)} {registry file path}\n");
exit(-1);
}
fdTcp = socket(AF_INET, SOCK_STREAM, 0);
bzero(&si_minhaTCP, sizeof(si_minhaTCP));
si_minhaTCP.sin_family = AF_INET;
si_minhaTCP.sin_addr.s_addr = htonl(INADDR_ANY);
si_minhaTCP.sin_port = htons((short) atoi(argv[2]));
bind(fdTcp, (struct sockaddr*)&si_minhaTCP, sizeof(si_minhaTCP));
listen(fdTcp, 10);
fdUdp = socket(AF_INET, SOCK_DGRAM, 0);
si_minhaUDP.sin_family = AF_INET;
si_minhaUDP.sin_addr.s_addr = htonl(INADDR_ANY);
si_minhaUDP.sin_port = htons((short) atoi(argv[1]));
bind(fdUdp, (struct sockaddr*)&si_minhaUDP, sizeof(si_minhaUDP));
FD_ZERO(&rset);
maxfdp1 = max(fdTcp, fdUdp) + 1;
for (;;)
{
FD_SET(fdTcp, &rset);
FD_SET(fdUdp, &rset);
// select the ready descriptor
nready = select(maxfdp1, &rset, NULL, NULL, NULL);
if (FD_ISSET(fdTcp, &rset))
{
//handle tcp connection
}
if (FD_ISSET(fdUdp, &rset))
{
//handle udp connection
}
}
当我运行此代码并尝试使用 udp 客户端测试它时,它没有执行任何操作
但是,如果您以 root 身份运行该程序并且没有运行其他已使用该端口的程序,则可以使用低于 1024 的端口...