這是我的服務器程序在C主代碼:C中的TCP服務器 - 端口總是增加?
int main(int argc, char** argv)
{
int sock, connected, bytes_received, true = 1;
struct sockaddr_in server_addr, client_addr;
int sin_size;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket");
exit(1);
}
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &true, sizeof (int)) == -1) {
perror("Setsockopt");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[1]));
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero), 8);
if (bind(sock, (struct sockaddr *) &server_addr, sizeof (struct sockaddr))
== -1) {
perror("Unable to bind");
exit(1);
}
if (listen(sock, 5) == -1) {
perror("Listen");
exit(1);
}
printf("\nTCPServer Waiting for client on port 5000");
fflush(stdout);
while (1)
{
pthread_t child;
sin_size = sizeof (struct sockaddr_in);
connected = accept(sock, (struct sockaddr *) &client_addr, &sin_size);
printf("\n I got a connection from (%s , %d)\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
threadInfo info;
info.argumentsPassedToCode = argv;
info.connected = connected;
pthread_create(&child, NULL, interpretMessage, &info);
}
close(sock);
return 0;
}
我的服務器總是打印出傳入連接的IP,而且它是來自於該端口。我注意到端口一直在增加。
- 這是正常的嗎?如果不是,我做錯了什麼?
- 如果我的服務器運行了很長時間,它是否會耗盡端口?如果是這樣,會發生什麼?
你沒有表現interpretMessage'的'執行 - 它始終貼近'info.connection'?您可能想要使用諸如'lsof'的程序來列出您的服務器仍在使用的端口.... – 2011-03-31 05:04:04