白天TCP客户端中的连接错误

时间:2018-08-18 01:43:19

标签: c sockets network-programming

我做错了什么,因为我无法获得白天的输出。代码对我来说看起来不错。另外,为什么我们在inet_pton中将第三个参数指定为&serverAddress.sin_addr ,而不是&serverAddress.sin_addr.s_addr

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

#define MAXLINE 4096

int main(int argc, char **argv)
{
    int sockfd, n;
    char receiveLine[MAXLINE +1];
    struct sockaddr_in serverAddress;

    if(argc != 2)
    {
        printf("\nUsage: a.out <IPaddress>\n");                                  //First Argument is FileName, Second should be IP Address
        exit(0);
    }

    if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {       
        printf("Socket error\n");
        exit(0);
    }

    bzero(&serverAddress, sizeof(serverAddress));
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(4455);

    if(inet_pton(AF_INET, argv[1], &serverAddress.sin_addr) <= 0)            //Presentation to Network.
    {   
        printf("inet_pton error for %s",argv[1]);
        exit(0);
    }

    if(connect(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress))<0)
    {
        printf("connect error");
        exit(0);
    }

    while( (n = read(sockfd, receiveLine, MAXLINE)) > 0)
    {
        receiveLine[n] = 0;
        if(fputs(receiveLine, stdout) == EOF)
        {       
            printf("fputs error");
            exit(0);
        }
    }

    if(n < 0)
    {   
        printf("read error");
        exit(0);
    }
    exit(0);    
}

1 个答案:

答案 0 :(得分:0)

(代表问题作者发布的解决方案)

我很笨,甚至忘记了监听端口。使用“ nc -l localhost 4455”。