简体   繁体   中英

Connect() Returns 0 Linux Socket programming (c/c++)

So I am trying to write a simple c++ socket program (Ubuntu) where all it does is connect to google and tells me it did so (Through port 80). I decide to print out the results of the connect() and socket commands. Here is the code:

#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<iostream> 
int main(int argc , char *argv[])
{
    int socket_desc;
    struct sockaddr_in server;

    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    std::cout << socket_desc;
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }

    server.sin_addr.s_addr = inet_addr("172.217.12.46");
    server.sin_family = AF_INET;
    server.sin_port = htons( 80 );

    //Connect to remote server
    std::cout << (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)));
    if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)    
    {
        puts("connect error");
        return 1;
    }

    puts("Connected");
    return 0;
}

Output of code:

30connect error

(It was late at night and I was too lazy to do line breaks)

So my question is: Does 0 mean no data was sent or the connection was not established? Why does it execute the connect error line of code even though 0 = 0 not less than 0?

Any Help is appreciated!

The return value of 0 from connect() means that the connection succeeded.

But immediately after you print the return value from connect() -- directly into std::cout using the << operator -- the shown code calls connect() a second time with the same socket.

That is an error, because the socket is already connected, and that's why your if() statement reports an error. You called connect() twice. That's your bug.

this :

 //Connect to remote server
std::cout << (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)));
if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)    
{
    puts("connect error");
    return 1;
}

to :

//Connect to remote server
result = connect(socket_desc , (struct sockaddr *)&server , sizeof(server));
std::cout << "connect result : " << result << std::endl;
if (result < 0)    
{
    puts("connect error");
    return 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM