Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

c++ - connect() does not return

I want to simply connect to a server and get a response. My program is written in c++, and you can see the code here:

if((interpreterSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
    return SOCKETERR;
}

fcntl(interpreterSocket, F_SETFD, FD_CLOEXEC);
setsockopt(interpreterSocket, SOL_SOCKET, SO_REUSEADDR, (char *) &flag, sizeof(flag));
setsockopt(interpreterSocket, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(flag));
setsockopt(interpreterSocket, SOL_SOCKET, SO_REUSEADDR , (char *) &flag, sizeof(flag));

address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(INTERPRETERADDR); 
address.sin_port = htons(INTERPRETERPORT);
adlen = sizeof(address);

if((rc = connect(interpreterSocket, (struct sockaddr *) &address, adlen)) < 0)
{
     close(interpreterSocket);
     return SOCKETERR;
}

The problem is when I run this program sometimes it has some trouble, so I have to kill the process. After that when I run the program, the connect function does not return and the program stops at the if line. I think this problem most be related to a socket that does not close in a proper manner.

I should mention that I run this program in CentOS.

Thanks in advance.

EDIT

I had one more problem, that caused the program stop at connect() function and it was some routing problems at the server.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are using blocking socket so connect blocks until it connects to server or timeout passes. To set sockets to non-blocking, you should use ioctlsocket function, exactly with FIONBIO command as second argument.

Remark that when you set sockets to non-blocking, you should start using select function to read or write to socket.

EDIT

Sorry, i forgot that's about Linux. It is possible to do nonblocking I/O on sockets by setting the O_NONBLOCK flag on a socket file descriptor using fcntl.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...