我正在研究一个关于c和java中的套接字编程的项目,使用UDP和TCP(当然是分开的)。我的UDP服务器是Java,我的UDP客户端是C.我遇到了一个问题,在我调用recvfrom()之后,printf和fprintf等方法实际上并没有打印所有内容。我也试过fflush。这是代码部分:
int main(int argc, char **argv) {
int sockfd, portno, n;
int serverlen;
struct sockaddr_in serveraddr;
struct hostent *server;
char *hostname;
char buf[BUFSIZE];
int GID = 9;
/* check command line arguments and extract port numbers */
if (argc != 4) {
fprintf(stderr,"usage: %s <hostname> <port> <myport>\n", argv[0]);
exit(0);
}
hostname = argv[1];
int serverPort = atoi(argv[2]);
int myPort = atoi(argv[3]);
int portRange = (5 * GID) + 10010;
if (myPort < portRange || myPort > portRange + 4) {
fprintf(stderr, "Invalid Port range\n");
exit(1);
}
/* socket: create the socket */
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
error("ERROR opening socket\n");
/* gethostbyname: get the server's DNS entry */
server = gethostbyname(hostname);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host as %s\n", hostname);
exit(0);
}
/* build the server's Internet address */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(serverPort);
/* create a message */
bzero(buf, BUFSIZE);
buf[0] = 74;
buf[1] = 111;
buf[2] = 121;
buf[3] = 33;
buf[4] = (myPort >> 8);
buf[5] = (myPort & 0xFF);
buf[6] = GID;
/* send the message to the server */
serverlen = sizeof(serveraddr);
n = sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&serveraddr,
serverlen);
if (n < 0)
error("ERROR in sendto\n");
bzero(buf, BUFSIZE);
/* print the server's reply if buf[6] != 0*/
n = recvfrom(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&serveraddr,
&serverlen);
//ERROR OCCURS AFTER RECEIVING
if (n < 0)
error("ERROR in recvfrom\n");
if (buf[6] == 0 && buf[7] == 1) {
printf("ERROR: no magic number\n");
return 0;
}
else if (buf[6] == 0 && buf[7] == 2) {
printf("ERROR: incorrect length\n");
return 0;
}
else if (buf[6] == 0 && buf[7] == 4) {
printf("ERROR: port number out of range\n");
}
printf("%.*s\n", strlen(buf), buf);
return 0;
}
答案 0 :(得分:2)
常见问题。您忽略了recvfrom()
返回的计数:
printf("%.*s\n", strlen(buf), buf);
应该是
printf("%.*s\n", n, buf);
注意您的recvfrom()
来电也不正确。它应该是:
n = recvfrom(sockfd, buf, sizeof buf, 0, (struct sockaddr *)&serveraddr,
&serverlen);
如果n < 0
,则不应输入以下if-else链。