【发布时间】:2017-11-29 14:40:50
【问题描述】:
我正在使用 UDP 和 TCP(当然是分开的)在 c 和 java 中进行有关套接字编程的项目。我的 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;
}
【问题讨论】:
-
什么是“BUFSIZE”?
-
你收到的buf null终止了吗?
-
'bzero(buf, BUFSIZE)', 然后 'n = recvfrom(sockfd, buf, strlen(buf)....', 'recvfrom nothing'. 所有 strlen() 调用网络代码非常可疑并且很可能是错误的。发布到 SO 的所有 C 网络代码中,有任何 strlen 的 99% 都是错误的。
-
recvfrom() 的长度指定为“strlen(buf)”... 在您使用 bzero() 清除它之后...
-
发布到 SO 的所有 C 网络代码中有很大一部分包含任何 'printf("%s...' 也是可疑的:(