Hi, i am trying to make a server client application using sockets in C.
Server and client compile just fine but they dont seem to connect with each other and i don't understand why (i just started learning about sockets).
My OS is SunOs 5.10.

This is my server code :

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define BUFLEN 500


int main(int argc, char *argv[])
{
    int sockfd, connectfd;
    int addr_len;
    char send [BUFLEN], receive [BUFLEN];
    pid_t    childpid;
    socklen_t    childlen;

    struct sockaddr_in    server_addr, child_addr, client_addr;

    if  ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror ("Error1 : Cannot create socket!");
        exit(1);
    }
     else
    {
        printf("Socket OK! \n");
        fflush(stdout);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons (5568);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    bzero(&server_addr,sizeof(server_addr));

    if  (bind(sockfd, (struct sockaddr *)&server_addr, sizeof (struct sockaddr) ) == -1)
    {
        perror("Error1: Unable to bind");
        exit(1);
    }
    else
    {
        printf("Server bind OK! \n");
        fflush(stdout);
    }

    if  (listen(sockfd, 5) == -1)
    {
        perror("Error1: Listen");
        exit(1);
    }
     else
    {
        printf("Server is listening! \n");
        fflush(stdout);
    }

    printf("\nWaiting for client on port 5000");
    fflush(stdout);
while (1)
{
    addr_len = sizeof(struct sockaddr_in);
    connectfd = accept(sockfd, (struct sockaddr *)&client_addr, &addr_len);
    printf("\nConnected with: (%s , %d)",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
}
close (connectfd);
close(sockfd);

return 0;
}

Changed :

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons (5568);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bzero(&server_addr,sizeof(server_addr));

To :

bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons (5568);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

Works fine now. Thank you

Member Avatar for Mouche

In this case, the bzero() function is used to clear the server_addr struct by filling it with zeroes. So before, you were clearing the struct after you had written to it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.