Home > Enterprise >  issues with connect function
issues with connect function

Time:01-19

I'm trying to get started on socket programming in c and I was following a few guides. but I'm always getting the error:

warning: 

passing argument 2 of ‘connect’ from incompatible pointer type [-Wincompatible-pointer-types]
   45 | int status= connect(socket_desc , (struct sockaddr *) &server , sizeof(server));
      |                                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~
      |                                   |
      |                                   struct sockaddr *

it wants struct sockaddr * to be constant but when I try to make it constant, the connect funtion doesn't have enough arguments.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main (){

    int netsocket;
    netsocket = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port   = htons(9002); 
    server.sin_addr.s_addr   = INADDR_ANY;

    int Verbindungsstatus = connect(netsocket, (struct sockaddr *) &server, sizeof(server));
    if (Verbindungsstatus == -1){
        printf("Connection error");
    }
    printf("Connected!");
    return 0;
}

CodePudding user response:

From the man page:

int connect(int sockfd, const struct sockaddr *addr,
                   socklen_t addrlen);

The second argument expects a const struct sockaddr *addr.

Perhaps try casting to (const struct sockaddr *) instead of (struct sockaddr *).

New code should use getaddrinfo instead of manually filling the struct. See the man page for an example: https://man7.org/linux/man-pages/man3/getaddrinfo.3.html

Aside: socket() may fail.

netsocket = socket(AF_INET, SOCK_STREAM, 0);```

Check its return value.

errno = 0;
if ((netsocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
}
  • Related