linux下UDP 客户端和服务端程序示例,使用recvfrom与sendto函数
程序转自hoyt的<Linux网络编程>,解决了作者的client端收不到数据的情况,但因为联系不到作者,只好在此贴出,如果有哪位朋友可以代我通知作者的或告诉我作者联系方式的话,本人不胜感激.
原程序错误原因:server端使用recvfrom()前为将用来标识记录地址的sockadd_in addr的addrlen为初始化,导致server端解析地址错误.
解决方法:将addrlen初始化为sizeof(addr)
/**/
/**********UDP服务端程序UDPserver.c***********/
#include < sys / types.h >
#include < sys / socket.h >
#include < netinet / in .h >
#include < arpa / inet.h >
#include < unistd.h >
#include < stdio.h >
#include < stdlib.h >
#include < errno.h >
#include < string .h >
#define SERVER_PORT 8888
#define MAX_MSG_SIZE 1024
void udps_respon( int sockfd) ... {
struct sockaddr_in addr;
unsigned int addrlen;
int n;
char msg[MAX_MSG_SIZE];
while(1) ...{
// 从网络上读,写到网络上去
#include < sys / types.h >
#include < sys / socket.h >
#include < netinet / in .h >
#include < arpa / inet.h >
#include < unistd.h >
#include < stdio.h >
#include < stdlib.h >
#include < errno.h >
#include < string .h >
#define SERVER_PORT 8888
#define MAX_MSG_SIZE 1024
void udps_respon( int sockfd) ... {
struct sockaddr_in addr;
unsigned int addrlen;
int n;
char msg[MAX_MSG_SIZE];
while(1) ...{
// 从网络上读,写到网络上去