2011-01-30 120 views
1

當試圖創建一個簡單的UDP客戶端時,我的代碼成功地打開了套接字並從文件中讀入一個小緩衝區,以通過命令行發送到由主機地址和端口號指定的服務器參數。錯誤的文件描述符 - 簡單的UDP客戶端

但是,sendto和recvfrom都以「壞文件描述符」失敗,我找不到原因。

void main(int argc, char* argv[]){ 
int s, n=0, obytes, inbytes; 
struct sockaddr_in sin; 
char *buffer; 
int address = 0; 

//Checks socket 
if((s = socket(AF_INET, SOCK_DGRAM, 0))<0) { 
    printf("Error creating socket\n"); 
    exit(0); 
} 
//Resets values in socket structure 
memset((char*)&sin, 0, sizeof(sin)); 
sin.sin_port = htons(atoi(argv[2])); 
sin.sin_family = AF_INET; 
sin.sin_addr.s_addr = inet_addr(argv[1]); 
printf("%d\n", sin.sin_addr.s_addr); 
/*Opens file to be sent and reads into buffer*/ 
FILE *readFile; 
readFile = fopen(argv[3], "r"); 
//Checks if file to be read can be opened 
if (readFile==NULL) { 
    perror ("Error opening file"); 
} 
//Reads in all the characters to a buffer 
else{ 
    while (!feof(readFile)) { 
     buffer[n] = fgetc (readFile); 
     n++; 
    } 

buffer[n] = '\0'; 
printf ("Total number of bytes: %d\n", n); 
for(int i = 0; i< n; i++){ 
    printf("%c", buffer[i]); 
} 
} 
printf("File was opened\n"); 
//Sends the buffer to the destination designated by the socket structure and checks to see if bytes were sent 
if((obytes = sendto(s, buffer, strlen(buffer), 0, (struct sockaddr *)&sin, sizeof(sin))) == -1) { 
    perror("Sendto() error!"); 
    exit(1); 
} 
printf("%d bytes were sent\n",obytes); 
//Receives response from the server and checks to see if bytes were actually received 
/* if((inbytes = recvfrom(s, buffer, strlen(buffer)+28, 0, (struct sockaddr *)&sin, sizeof(struct sockaddr*))) == -1) { 
    perror("Recvfrom() error!"); 
    exit(1); 
}*/ 
printf("%d bytes were received.\n", inbytes); 
//Closes file 
fclose (readFile); 

} 
+0

把你的代碼的輸出,printf我的意思是。 – 2011-01-30 16:46:39

回答

1

沒有輸出,這是一種很難,但我注意到的第一件事是,你永遠不分配的緩衝區寫在文件

4

我看到一些錯誤/問題:

  • 您從未將n設置爲文件的長度
  • 沒有內存分配來保存文件
  • 一次讀取一個字節的文件將會l條很inefficent
  • 加載你應該知道該文件的長度的文件後,無需使用strlen()
  • 如果是二進制文件,strlen()會失敗,因爲它會在與第一個嵌入字節停止值0