我正在从事一个有关 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;
最佳答案
常见问题。您忽略了 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 链。
关于c - C 中的 UDP 套接字编程,调用 recvfrom() 后 printf 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47546055/