2014-09-27 86 views
2

分段錯誤通常出現在內存分配或管理出現錯誤時。但在這種情況下,我不知道什麼是錯的。任何建議都會有幫助。我正嘗試連接到select()服務器。分段錯誤:11,在TCP客戶端

#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; 
} 
+0

公平的警告'close(socket);'在失敗'gethostbyname()'的情況下會關閉一個不確定的'int'值。這行代碼甚至不應該在那裏。我正在爭論+ 1,因爲你顯然至少試圖通過散佈的'printf'來進行調試,坦率地說,這比大多數人所承擔的要多得多。 – WhozCraig 2014-09-27 04:19:21

+0

我無法理解,所以我刪除了關閉套接字語句,但仍然收到相同的錯誤。 – 2014-09-27 04:19:41

+0

如果你不介意我的問題,你是如何使用Unix套接字編程的一般指南的。 [** Beej的網絡編程指南**](http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html),有點過時了,但相對於大多數來說相當不錯,如果你還沒有這樣的例子,這些例子會非常有幫助。 – WhozCraig 2014-09-27 04:21:00

回答

1

由於WhozCraig提到,問題是你沒有提供主機名或IP地址。 您是否正在檢查提供的參數數目!

我運行你的程序,並沒有發現任何段錯誤與正確的參數,即host_name提供。

你應該包括以下檢查:

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

這將不允許如果沒有提供主機名的程序進行。

運行程序爲./<excecutable> <host_name>

嘗試與本地主機第一。

./tcp_client localhost

希望這有助於!