[英]UDP Socket Programming in C, printf not working after calling recvfrom()?
我正在一個有關使用UDP和TCP(當然是單獨使用)在c和java中進行套接字編程的項目。 我的UDP服務器是Java,而UDP客戶端在C中。我遇到了一個問題,在我調用recvfrom()之后,諸如printf和fprintf之類的方法實際上並未打印所有內容。 我也試過花lush。 這是這段代碼:
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鏈。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.