我有一個(gè)簡單的程序來檢查端口是否打開,但是我想縮短套接字連接的超時(shí)時(shí)間,因?yàn)槟J(rèn)值太長了。我不確定如何執(zhí)行此操作。這是代碼:#include <sys/socket.h>#include <sys/time.h>#include <sys/types.h>#include <arpa/inet.h>#include <netinet/in.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <netdb.h>#include <stdlib.h>#include <string.h>#include <unistd.h>int main(int argc, char **argv) { u_short port; /* user specified port number */ char addr[1023]; /* will be a copy of the address entered by u */ struct sockaddr_in address; /* the libc network address data structure */ short int sock = -1; /* file descriptor for the network socket */ if (argc != 3) { fprintf(stderr, "Usage %s <port_num> <address>", argv[0]); return EXIT_FAILURE; } address.sin_addr.s_addr = inet_addr(argv[2]); /* assign the address */ address.sin_port = htons(atoi(argv[2])); /* translate int2port num */ sock = socket(AF_INET, SOCK_STREAM, 0); if (connect(sock,(struct sockaddr *)&address,sizeof(address)) == 0) { printf("%i is open\n", port); } close(sock); return 0;}
3 回答

夢(mèng)里花落0921
TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊
關(guān)于使用select()/ 的答案poll()是正確的,應(yīng)該以這種方式編寫代碼以便于移植。
但是,由于您使用的是Linux,因此可以執(zhí)行以下操作:
int synRetries = 2; // Send a total of 3 SYN packets => Timeout ~7s
setsockopt(fd, IPPROTO_TCP, TCP_SYNCNT, &synRetries, sizeof(synRetries));
請(qǐng)參閱man 7 tcp和man setsockopt。
我使用它來加快我需要快速修補(bǔ)的程序中的連接超時(shí)。不能通過select()/將其黑客破解為超時(shí)poll()。
- 3 回答
- 0 關(guān)注
- 663 瀏覽
添加回答
舉報(bào)
0/150
提交
取消