UDP服务器没有收到UDP客户端程序发送的数据。我觉得我在UDP Server程序中做错了。感谢。
send_client_message = malloc(message_size);
recv_client_message = malloc(message_size);
sockaddr_in_length = sizeof(struct sockaddr_in);
/* Create a datagram socket.*/
server_sock = socket(AF_INET,SOCK_DGRAM,0);
if (server_sock == return_error)
{
printf("Error in opening a datagram socket\n");
exit(0);
}
printf("Host sock = %d\n",server_sock);
/* Bind a local name to the socket.*/
server_sockaddr_in.sin_family = AF_INET;
server_sockaddr_in.sin_port = 4999;
server_sockaddr_in.sin_addr.s_addr = INADDR_ANY;
rc = bind(server_sock,(struct sockaddr *)&server_sockaddr_in,
sockaddr_in_length);
if (rc == return_error)
{
printf("Error in binding - \n");
(void)close(server_sock);
exit(0);
}
/* Get the server information, and print its data out.*/
rc = getsockname(server_sock,(struct sockaddr *)&server_sockaddr_in,
&sockaddr_in_length);
if (rc != return_error)
{
printf("Server Information\n");
printf("--------------------------------\n");
printf("Server sock - %d\n",server_sock);
printf("Server IP address - %x\n",
server_sockaddr_in.sin_addr.s_addr);
printf("Server port # - %d\n\n",
server_sockaddr_in.sin_port);
}
optval = message_size;
optlen = sizeof(optval);
rc = setsockopt(server_sock,SOL_SOCKET,SO_SNDBUF,(char *)&optval,
optlen);
if (rc == return_error)
{
//printf("Error in setsockopt - %d\n",sock_errno());
printf("Error in setsockopt - \n");
(void)close(server_sock);
exit(0);
}
printf(".... Ready for clients ....\n");
/* Loop forever */
for (;;)
{
/* Monitor incoming buffers. */
rc = recvfrom(server_sock,recv_client_message,message_size,0,
(struct sockaddr *)&client_sockaddr_in,
&sockaddr_in_length);
printf("Recieved packet from %s: %d\nData: %s\n\n", inet_ntoa(client_sockaddr_in.sin_addr), ntohs(client_sockaddr_in.sin_port), recv_client_message);
fflush(stdout);
if (rc == return_error)
{
printf("Error in receiving message \n");
break;
}
} /* end of for(;;) */
/* Return the socket back to the system and exit normally. */
rc = close(server_sock);
if (rc == return_error)
{
printf("Error in closing the socket \n");
exit(0);
}
printf("Datagram server terminated\n");
exit(0);
}
for(i = 0; i < NPACK; i += 1) {
printf("Sending packet %d\n", i);
sprintf(buf, "This is packet %d\n", i);
if(sendto(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, slen) == -1)
diep("sendto()");
}
close(s);
return 0;
}
答案 0 :(得分:3)
server_sockaddr_in.sin_port = 4999;
您可能想要htons
那个4999。