套接字编程连接错误

时间:2013-11-29 09:54:06

标签: sockets tcp ip

I received the error: `connect failed: connection refused` from the following code. Server side code runs fine, but when I run the client side I get the connect failed error. I am using Ubuntu.

server side run: `./server.out 1234`  
client side run: `.client.out 127.0.0.1 input.txt 1234`

Client code:

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

    // check error 
    void DieWithError(char *errorMessage)
    {
        perror(errorMessage);
        exit(1);
    }
    void DieWithUserMessage(const char *msg, const char *detail) {
      fputs(msg, stderr);
      fputs(": ", stderr);
      fputs(detail, stderr);
      fputc('\n', stderr);
      exit(1);
    }

    void DieWithSystemMessage(const char *msg) {
      perror(msg);
      exit(1);
    }
    //define buffer size
    enum sizeConstants {
      MAXSTRINGLENGTH = 128,
      BUFSIZE = 512,
    };

    int main(int argc, char *argv[]) {
    char buffer[BUFSIZE];
    //FILE *fp,*fpOut; // declare file pointer

        if (argc < 3 || argc > 4) // Test for correct number of arguments
            DieWithUserMessage("Parameter(s)","<Server Address> <Echo Word> [<Server Port>]");

        char *servIP = argv[1];     // First arg: server IP address (dotted quad)
        char *echoString = argv[2]; // Second arg: string to echo

        // Third arg (optional): server port (numeric).  7 is well-known echo port
        in_port_t servPort = (argc == 4) ? atoi(argv[3]) : 7;

        // Create a reliable, stream socket using TCP
        int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (sock < 0)
            DieWithSystemMessage("socket() failed");

        // Construct the server address structure
        struct sockaddr_in servAddr;            // Server address
        memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure
        servAddr.sin_family = AF_INET;          // IPv4 address family
        // Convert address
        int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
        if (rtnVal == 0)
            DieWithUserMessage("inet_pton() failed", "invalid address string");
        else if (rtnVal < 0)
             DieWithSystemMessage("inet_pton() failed");
             servAddr.sin_port = htons(servPort);    // Server port

      // Establish the connection to the echo server
      if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
        DieWithSystemMessage("connect() failed");
        /*
            //start reading file input from computer
            char buf[1000];
            fp =fopen("input.txt","r");//open the file
            if (!fp){
                    printf("it failed!\n");
                    return 1;
                }
            while(fgets (buf, 1000, fp)!=NULL) { // take the file input value in buf char array


            //printf("The input value in program.txt file: %s",buf);
            printf("Received Message from server: ");                            
          */

            size_t echoStringLen = strlen(echoString); // Determine input length

          // Send the string to the server
            ssize_t numBytes = send(sock, echoString, echoStringLen, 0);
            if (numBytes < 0)
               DieWithSystemMessage("send() failed");
            else if (numBytes != echoStringLen)
              DieWithUserMessage("send()", "sent unexpected number of bytes");

      // Receive the same string back from the server
      unsigned int totalBytesRcvd = 0; // Count of total bytes received
          // Setup to print the echoed string

          while (totalBytesRcvd < echoStringLen) {
             // I/O buffer
            /* Receive up to the buffer size (minus 1 to leave space for
             a null terminator) bytes from the sender */
            numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
            if (numBytes < 0)
              DieWithSystemMessage("recv() failed");
            else if (numBytes == 0)
              DieWithUserMessage("recv()", "connection closed prematurely");
            totalBytesRcvd += numBytes; // Keep tally of total bytes
            buffer[numBytes] = '\0';    // Terminate the string!
            printf("%s",buffer);

            //fputs(buffer, stdout);      // Print the echo buffer
         }

        //fpOut = fopen("gcd.txt","w"); // open the gcd txt file in write mode
        //fprintf(fpOut,"%s",buffer );// write the gcd value in gcd text file
        //fputc('\n', stdout);
        //fclose(fpOut);
        //fclose(fp);
            return 0;




    close(sock);
    exit(0);
    }

Server code:

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

    void DieWithError(char *errorMessage)
    {
        perror(errorMessage);
        exit(1);
    }
    void DieWithUserMessage(const char *msg, const char *detail) {
      fputs(msg, stderr);
      fputs(": ", stderr);
      fputs(detail, stderr);
      fputc('\n', stderr);
      exit(1);
    }

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

    static const int MAXPENDING = 5; // Maximum outstanding connection requests

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

      if (argc != 2) // Test for correct number of arguments
        DieWithUserMessage("Parameter(s)", "<Server Port>");

      in_port_t servPort = atoi(argv[1]); // First arg:  local port


      // Create socket for incoming connections
      int servSock; // Socket descriptor for server
      if ((servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        DieWithSystemMessage("socket() failed");

      // Construct local address structure
      struct sockaddr_in servAddr;                  // Local address
      memset(&servAddr, 0, sizeof(servAddr));       // Zero out structure
      servAddr.sin_family = AF_INET;                // IPv4 address family
      servAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface
      servAddr.sin_port = htons(servPort);          // Local port

      // Bind to the local address
      if (bind(servSock, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0)
        DieWithSystemMessage("bind() failed");

      // Mark the socket so it will listen for incoming connections
      if (listen(servSock, MAXPENDING) < 0)
        DieWithSystemMessage("listen() failed");

      for (;;) { // Run forever
        struct sockaddr_in clntAddr; // Client address
        // Set length of client address structure (in-out parameter)
        socklen_t clntAddrLen = sizeof(clntAddr);
        printf("\nIam here\n");
        // Wait for a client to connect
        int clntSock = accept(servSock, (struct sockaddr *) &clntAddr, &clntAddrLen);
        if (clntSock < 0)
          DieWithSystemMessage("accept() failed");

        // clntSock is connected to a client!

        char clntName[INET_ADDRSTRLEN]; // String to contain client address


        if (inet_ntop(AF_INET, &clntAddr.sin_addr.s_addr, clntName,sizeof(clntName)) != NULL)
         printf("Got response from client: %s/%d\n", clntName, ntohs(clntAddr.sin_port));
        else
          puts("Unable to get client address");

        HandleTCPClient(clntSock);
      }
      // NOT REACHED
    }

HandleTCPClient:`#define RCVBUFSIZE 1024 / *接收缓冲区大小* /

void DieWithError(char errorMessage); / 错误处理函数* /

void HandleTCPClient(int clntSocket) {
        FILE *fp;
        char echoBuffer[RCVBUFSIZE];        /* Buffer for echo string */
        int recvMsgSize;                    /* Size of received message */

        /* Receive message from client */
        if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
        DieWithError("recv() failed");
        printf("Server asked file name from Client side:: %s", echoBuffer);
        fp =fopen("echoBuffer","r");//open the file
        if (!fp){
           printf("it failed!\n");
           //return 1;
        }

         //int i,j;
         //sscanf(echoBuffer, "%d %d", &i,&j);// take the two number from client and convert string to integer.
         //sprintf(echoBuffer,"%d",gcd(i,j)); // call the gcd method.

      /* Send received string and receive again until end of transmission */
        while (recvMsgSize > 0){      /* zero indicates end of transmission */

        /* Echo message back to client */
        if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize)
            DieWithError("send() failed");

        /* See if there is more data to receive */
        if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
            DieWithError("recv() failed");
        }
        fclose(fp);
        close(clntSocket);    /* Close client socket */
}

HandleTCPclient接收来自客户端的命令,如input.txt,并检查该文件并发送回客户端,但我得到了分段错误(核心转储)。这里input.txt只包含一个文本文件

在这里输入代码

1 个答案:

答案 0 :(得分:1)

您的代码未使用您提供的端口,但尝试连接到7,您可能没有运行echo服务器。尝试更改为

in_port_t servPort = (argc ==4) ? atoi(argv[3]) : 7;