看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): Fedora , C 問題(Question): 00000000 | 30 31 30 31 00 00 00 00 | 0 1 0 1 . . . . 00000010 | 30 30 30 30 00 00 00 00 | 0 0 0 0 . . . . 以上是餵給SERVER的資料,想要的資料是第二行的 0 0 0 0 但每次都只印出 0 1 0 1,想請問各位怎樣才能全部印出 ?? 朋友問我但我也不是很了解,所以請各位大大解惑,謝謝。 程式碼(Code): #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/errno.h> #define SERV_PORT 60000 #define MAXNAME 1024 extern int errno; main() { int socket_fd; /* file description into transport */ int recfd; /* file descriptor to accept*/ int length; /* length of address structure*/ int nbytes; /* the number of read */ char buf[BUFSIZ]; struct sockaddr_in myaddr; /* address of this service */ struct sockaddr_in client_addr; /* address of client */ /* Get a socket into TCP/IP */ if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) <0) { perror ("socket failed"); exit(1); } /*Set up our address*/ bzero ((char *)&myaddr, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(SERV_PORT); /* Bind to the address to which the service will be offered*/ if (bind(socket_fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) <0) { perror ("bind failed"); exit(1); } /* Set up the socket for listening, with a queue length of 5*/ if (listen(socket_fd, 20) <0) { perror ("listen failed"); exit(1); } /* Loop continuously, waiting for connection requests and performing the service*/ length = sizeof(client_addr); printf("Server is ready to receive !!\n"); printf("Can strike Cntrl-c to stop Server >>\n"); while (1) { if ((recfd = accept(socket_fd, (struct sockaddr_in *)&client_addr, &length)) <0) { perror ("could not accept call"); exit(1); } if ((nbytes = read(recfd, &buf, BUFSIZ)) < 0) { perror("read of data error nbytes !"); exit (1); } printf("Create socket #%d form %s : %d\n", recfd, inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port)); printf("%s\n", &buf); /* return to client */ if (write(recfd, &buf, nbytes) == -1) { perror ("write to client error"); exit(1); } close(recfd); printf("Can Strike Crtl-c to stop Server >>\n"); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.73.207.219 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1447832014.A.49C.html
yvb: 其實資料應該都有收到, 只是印的時候, 遇到字串結束字元. 11/18 15:51
yvb: 亂改: printf("%s\n", &buf); 改為 printf("%s\n", buf+010); 11/18 15:55
ms5566288: 再試試看,謝謝~~~ 11/18 16:40