Socket in C does not compile

0

I'm having trouble creating a C socket on Linux Ubuntu. I've done everything as the guy explains in class and my code does not compile.

Code

GNU nano 2.5.3                          Arquivo: socket.c                                                            

#include <stdio.h>
#include <netdb.h>

int main()
{
        int meusocket;
        int conecta;

        struct sockaddr_in alvo;

        meusocket  = socket(AF_INET, SOCKET_STREAM, 0);
        alvo.sin_family = AF_INET;
        alvo.sin_port = htons(80);
        alvo.sin_addr.s_addr = inet_addr("192.168.0.1");

        conecta = connect(meusocket, (struct sockaddr *)&alvo, sizeof alvo);

        if(conecta == 0)
        {
                printf("Porta aberta \n");
                close(meusocket);
                close(conecta);
        }else{
                printf("Porta Fechada \n");
        }
}

Error When Compiling

socket.c: In function ‘main’:
socket.c:11:31: error: ‘SOCKET_STREAM’ undeclared (first use in this function)
  meusocket  = socket(AF_INET, SOCKET_STREAM, 0);
                               ^
socket.c:11:31: note: each undeclared identifier is reported only once for each function it appears in
socket.c:14:25: warning: implicit declaration of function ‘inet_addr’ [-Wimplicit-function-declaration]
  alvo.sin_addr.s_addr = inet_addr("192.168.0.1");
                         ^
socket.c:21:3: warning: implicit declaration of function ‘close’ [-Wimplicit-function-declaration]
   close(meusocket);
    
asked by anonymous 24.12.2017 / 16:22

1 answer

0

suggest code:

  • embed the comments to the question
  • compile cleanly
  • documents why each header file is included
  • and now the proposed code

    #include <stdio.h>        // printf(), perror()
    #include <sys/types.h>    // AF_INET, SOCK_STREAM
    #include <sys/socket.h>   // socket(), connect()
    #include <netinet/in.h>   // struct sockaddr_in
    #include <arpa/inet.h>    // htons(), inet_addr()
    #include <unistd.h>       // close()
    //#include <netdb.h>
    
    int main( void )
    {
            int meusocket;
            int conecta;
    
            struct sockaddr_in alvo;
    
            meusocket  = socket(AF_INET, SOCK_STREAM, 0);
            alvo.sin_family = AF_INET;
            alvo.sin_port = htons(80);
            alvo.sin_addr.s_addr = inet_addr("192.168.0.1");
    
            conecta = connect(meusocket, (struct sockaddr *)&alvo, sizeof alvo);
    
            if(conecta == 0)
            {
                    printf("Porta aberta \n");
                    close(meusocket);
                    //close(conecta);
            }else{
                    perror( "connect falhou" );
                    printf("Porta Fechada \n");
            }
    }
    
        
    24.12.2017 / 18:00