在linux下玩轉(zhuǎn)帶有超時時間的connect函數(shù)
在之前的文章中,我們在Windows下玩過帶有超時時間的,本文我們在linux下來玩。在某次面試中,還被遇到了這個問題,有意思。
直接上客戶端代碼:
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <fcntl.h>
#include <time.h>
int main(int argc, char *argv[]) // 注意輸入?yún)?shù), 帶上ip和port
{
int sockClient = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addrSrv;
addrSrv.sin_addr.s_addr = inet_addr(argv[1]);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(atoi(argv[2]));
fcntl(sockClient, F_SETFL, fcntl(sockClient, F_GETFL, 0)|O_NONBLOCK);
int iRet = connect(sockClient, ( const struct sockaddr *)&addrSrv, sizeof(struct sockaddr_in));
printf("connect iRet is %d, errmsg:%s\n", iRet, strerror(errno)); // 返回-1不一定是異常
if (iRet != 0)
{
if(errno != EINPROGRESS)
{
printf("connect error:%s\n", strerror(errno));
}
else
{
struct timeval tm = {5, 0};
fd_set wset, rset;
FD_ZERO(&wset);
FD_ZERO(&rset);
FD_SET(sockClient, &wset);
FD_SET(sockClient, &rset);
int time1 = time(NULL);
int n = select(sockClient + 1, &rset, &wset, NULL, &tm);
int time2 = time(NULL);
printf("time gap is %d\n", time2 - time1);
if(n < 0)
{
printf("select error, n is %d\n", n);
}
else if(n == 0)
{
printf("connect time out\n");
}
else if (n == 1)
{
if(FD_ISSET(sockClient, &wset))
{
printf("connect ok!\n");
fcntl(sockClient, F_SETFL, fcntl(sockClient, F_GETFL, 0) & ~O_NONBLOCK);
}
else
{
printf("unknow error:%s\n", strerror(errno));
}
}
else
{
printf("oh, not care now, n is %d\n", n);
}
}
}
printf("I am here!\n");
getchar();
close(sockClient);
return 0;
}
服務(wù)端代碼,我們已經(jīng)寫過多次,本文就不寫了。
經(jīng)測試,上述程序OK, 用tcpdump抓包,還能學(xué)到不少東西,比如SYN包重傳,RST包等。有點意思。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
linux安裝jdk,tomcat 配置vsftp遠程連接的步驟
這篇文章主要介紹了linux安裝jdk,tomcat 配置vsftp遠程連接,需要的朋友可以參考下2015-04-04
在linunx系統(tǒng)中搭建靜態(tài)文件服務(wù)的流程步驟
在服務(wù)器上有一些文件,想共享給其他用戶下載,同時因為ftp和sftp被禁用,且使用起來不太方便,需要找一種搭建成本低,安全高效的方式來完成此功能,因此linux上的httpd服務(wù)是一個很好的選擇,所以本文給大家介紹了在linux系統(tǒng)中搭建靜態(tài)文件服務(wù)的流程步驟2024-02-02
linux下使用Apache+php實現(xiàn)留言板功能的網(wǎng)站
在linux下使用apache+php實現(xiàn)留言板功能的網(wǎng)站,首先需要我們的linux服務(wù)器上安裝apache和php,然后結(jié)合其他操作實現(xiàn)此功能,下文小編給大家介紹的非常詳細,感興趣的朋友一起學(xué)習(xí)吧2016-10-10
CentOS6.5下搭建文件共享服務(wù)Samba的教程
這篇文章主要介紹了CentOS6.5下搭建文件共享服務(wù)(Samba)的教程,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10

