#include int timeout_connect(const char* ip,int port,int time);

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

{

if(argc!=3){

printf("usage:./%s [server ip] [server port]\n",basename(argv[1]));

exit(EXIT_FAILURE);

}

const char* ip;

int client_fd,port,time;

ip=argv[1];

port=atoi(argv[2]);

time=10;

client_fd=timeout_connect(ip,port,time);

if(client_fd==-1)

{

close(client_fd);

exit(EXIT_FAILURE);

}

printf("connect success!\n");

close(client_fd);

exit(EXIT_SUCCESS);

}

int timeout_connect(const char* ip,int port,int time)

{

int client_fd;

//创建套接字

if((client_fd=socket(AF_INET,SOCK_STREAM,0))==-1){

perror("socket");

return -1;

}

//设置SO_SNDTIMEO超时选项

struct timeval timeout;

timeout.tv_sec=time;

timeout.tv_usec=0;

socklen_t time_len=sizeof(timeout);

if(setsockopt(client_fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,time_len)==-1){

perror("setsockopt");

return -1;

}

//初始化服务器地址

struct sockaddr_in server_address;

bzero(&server_address,sizeof(server_address));

server_address.sin_family=AF_INET;

server_address.sin_port=htons(port);

if(inet_pton(AF_INET,ip,&server_address.sin_addr)==-1){

perror("inet_pton");

return -1;

}

//连接服务端

printf("wait connect......\n");

int connect_ret_value;

if((connect_ret_value=connect(client_fd,(struct sockaddr*)&server_address,sizeof(server_address)))==-1){

if(errno==EINPROGRESS){

printf("connect timeout!\n");

return -1;

}

perror("connect");

return -1;

}

return client_fd;

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐