在C ++ Linux中的套接字超时 [英] Socket Timeout in C++ Linux

查看:206
本文介绍了在C ++ Linux中的套接字超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定首先我想提一下我做的是完全道德的,是我的端口扫描。

Ok first of all I like to mention what im doing is completely ethical and yes I am port scanning.

程序运行良好当端口打开,但当我得到一个封闭的套接字程序停止了很长时间,因为没有超时子句。下面是以下代码

The program runs fine when the port is open but when I get to a closed socket the program halts for a very long time because there is no time-out clause. Below is the following code

int main(){

	int err, net;
	struct hostent *host;
	struct sockaddr_in sa;

	sa.sin_family = AF_INET;

	sa.sin_port = htons(xxxx);
	sa.sin_addr.s_addr = inet_addr("xxx.xxx.xxx.xxx");

	net = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	err = connect(net, (struct sockaddr *)&sa, sizeof(sa));

	if(err >= 0){ cout << "Port is Open"; }
	else { cout << "Port is Closed"; }

}


$ b $ p我在堆栈溢出中发现了这个,对我使用 select()命令有意义。

问题是我们可以使connect()函数超时,所以我们不等待一年,它会回来一个错误?

Question is can we make the connect() function timeout so we dont wait a year for it to come back with an error?

推荐答案

最简单的是设置闹钟并且连接被信号中断(请参阅 UNP 14.2):

The easiest is to setup an alarm and have connect be interrupted with a signal (see UNP 14.2):


signal( SIGALRM, connect_alarm ); /* connect_alarm is you signal handler */
alarm( secs ); /* secs is your timeout in seconds */
if ( connect( fs, addr, addrlen ) < 0 )
{
    if ( errno == EINTR ) /* timeout */
        ...
}
alarm( 0 ); /* cancel alarm */

虽然使用选择并不困难:)

您也可以了解原始套接字

Though using select is not much harder :)
You might want to learn about raw sockets too.

这篇关于在C ++ Linux中的套接字超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆