分段故障:11,在TCP客户端

时间:2014-09-27 04:11:22

标签: c linux

当内存分配或管理出现错误时,通常会出现分段错误。但在这种情况下,我不确定什么是错的。任何建议都会有帮助。我正在尝试连接到select()服务器。

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

#define INPUT "Socket TCP"
#define BUF_SIZE 1024

int main(int argc, char *argv[]){
    int sockt;
    struct sockaddr_in serv;
    struct hostent *host;
    char buff[BUF_SIZE];


    serv.sin_family = AF_INET;

    /*host = argv[1];
     host = malloc (1 + strlen (argv[1]));
     */


    host = gethostbyname (argv[1]);
    printf("1");
    if(host == 0)
    {
        perror("gethostbyname failed");
        close(sockt);
        exit(1);
    }
    else
        printf("gethost name succeeded \n");

    sockt = socket(AF_INET, SOCK_STREAM, 0);
    printf("2");
    if(sockt < 0)
    {
        perror("socket failed");
        exit(1);
    }
    else
        printf("socket connected \n");

    printf("3");
    memcpy(&serv.sin_addr, host->h_addr, host->h_length);
    serv.sin_port = htons(1234); /*Convert from host byte order to network byte order*/
    printf("4");

    /*Condition to check if the client has connected*/
    if(connect(sockt, (struct sockaddr *) &serv, sizeof(serv)) <0)
    {
        perror("Failed to connect");
        close(sockt);
        exit(1);
    }
    else
        printf("5");

    /*Condition to check if the data is sent*/
    if(send(sockt, INPUT, sizeof(INPUT), 0) < 0)
    {
        perror("Failed to send the data");
        close(sockt);
        exit(1);
    }
    else
        printf("data sent");
    printf("The data sent is %s\n", INPUT);
    close(sockt);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

WhozCraig所述,问题是您没有提供主机名或IP地址。 你们都没有检查提供的参数数量!

我运行你的程序并没有发现任何带有正确参数的段错误,即提供了host_name。

您应该包括以下检查:

if(argc<2)
{
   printf("usage : %s hostname",argv[0]);
   exit(0);
}

如果没有提供主机名,则不允许程序继续。

./<excecutable> <host_name>

运行程序

首先尝试使用localhost。

即。 ./tcp_client localhost

希望这有帮助!

相关问题