简体   繁体   中英

Socket Programming

I have a simple server and a client. I run the server at some port in my machine and when I try to connect my client to the server, it says network is unreachable. Can someone please suggest me why is it not being able to connect to the server. Please have a look at the files below:

server.c

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

void error(const char *msg)
{
    perror(msg);
    exit(1);
}

int main(int argc, char *argv[]){

    int sockfd, newsockfd, portno;
    struct sockaddr_in serv_addr;
    char sendmessage[50];

    if(argc != 2){
        fprintf(stderr, "ERROR, Port number not provided or Command line argument is not 2\n");
        exit(1);
    }

    //creating a socket for the server
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        error("ERROR opening socket");
    }

    portno = atoi(argv[1]);

    //describing the attributes for socket address
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);

    if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
        error("Error on binding the socket");
        exit(1);
    }

    //allowing only 1 client to connect to the server at a time
    if(listen(sockfd, 1) < 0){
        error("Error in listening to the socket");
    }

    printf("Server is running...... \nWaiting for the connection from the client on port: %d\n", portno);

    while(1){
        //accepts the connection from the client
        newsockfd = accept(sockfd, (struct sockaddr*)NULL, NULL);

        if(newsockfd < 0){
            error("Error on accepting");
        }

        strcpy(sendmessage, "Welcome to The Server");
        write(newsockfd, sendmessage, strlen(sendmessage));
    }
    return 0;
}

client.c

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

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char* argv[]){

    int sockfd;
    char recvmessage[100];
    char sendmessage[100];
    int portno;
    struct hostent *server;

    struct sockaddr_in serv_addr;

    if(argc != 3){
        fprintf(stderr, "Error, either IP address or port number not provided.\n");
        exit(1);
    }

    portno = atoi(argv[2]);

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if(socket < 0){
        error("Error with creating a socket");
    }

    //check whether the host exist or not
    server = gethostbyname(argv[1]);

    if(server == NULL){
        fprintf(stderr, "ERROR, the host is not defined\n");
        exit(0);
    }

    //creating the socket
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);

    //connecting the client to the socket
    if(connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
        error("Could not connect to the server......");
        exit(1);
    }

    printf("Connection Successful to the Server\n");
    return 0;
}

First of all make sure you pass the same port number to both server & client . If the port number is different, communication between server and client won't happen.

Here is the code for local machine. You can change the code a little and pass IP addresses.

Server.c

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

#define PORTNUM 2348

#define bufferLength 500


int main(int argc, char *argv[])
{ 

    char buffer[bufferLength];

    struct sockaddr_in dest; /* socket info about the machine connecting to us */
    struct sockaddr_in serv; /* socket info about our server */
    int mysocket;            /* socket used to listen for incoming connections */
    socklen_t socksize = sizeof(struct sockaddr_in);

    memset(&serv, 0, sizeof(serv));           /* zero the struct before filling the fields */
    serv.sin_family = AF_INET;                /* set the type of connection to TCP/IP */
    serv.sin_addr.s_addr = htonl(INADDR_ANY); /* set our address to any interface */
    serv.sin_port = htons(PORTNUM);           /* set the server port number */    

    mysocket = socket(AF_INET, SOCK_STREAM, 0);

    /* bind serv information to mysocket */
    bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));

    /* start listening, allowing a queue of up to 1 pending connection */
    listen(mysocket, 1);


    int consocket;

    int cpid;

    while(1)
    {

          consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);

          perror("consocket\n");

          if( (cpid = fork()) == 0 )
          {
            printf("inside child process\n\n\n");

            close(mysocket);

            close(consocket);

            int recivedBytes = recv(consocket, buffer, bufferLength, 0);

            buffer[recivedBytes] = '\0'; 

            printf("recieved data %s \n", buffer);  

            return 0;   
          }
          else
            close(consocket);

    }

    close(mysocket);

    return EXIT_SUCCESS;
}

Client.c

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

#define PORTNUM 2348


int main(int argc, char *argv[])
{
   char buffer[] = "My name is khan"; /* +1 so we can add null terminator */
   int len, mysocket;
   struct sockaddr_in dest; 


   mysocket = socket(AF_INET, SOCK_STREAM, 0);

   memset(&dest, 0, sizeof(dest));                /* zero the struct */
   dest.sin_family = AF_INET;
   dest.sin_addr.s_addr = inet_addr("127.0.0.1"); /* set destination IP number */ 
   dest.sin_port = htons(PORTNUM);                /* set destination port number */

   connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));

   len = send(mysocket, buffer, strlen(buffer), 0); 
  perror("len\n");

   /* We have to null terminate the received data ourselves */
   buffer[len] = '\0';

   printf("sent %s (%d bytes).\n", buffer, len);

   close(mysocket);
   return EXIT_SUCCESS;
}

Hope this helps

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