作者ms5566288 (Elaker)
看板C_and_CPP
标题[问题] 如何使用TCPSERVER印出完整资料 ??
时间Wed Nov 18 15:33:31 2015
开发平台(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://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1447832014.A.49C.html
1F:推 yvb: 其实资料应该都有收到, 只是印的时候, 遇到字串结束字元. 11/18 15:51
2F:→ yvb: 乱改: printf("%s\n", &buf); 改为 printf("%s\n", buf+010); 11/18 15:55
3F:→ ms5566288: 再试试看,谢谢~~~ 11/18 16:40