用UDP数据报发送数据给本机,数据可以发出去,但是服务端(本机)却接收不到任何数据,刚接触网络,请指教!
服务器端:
SOCKET server_socket_udp;
sockaddr_in server_address_udp,from_address_udp;
char server_data[20]="你好";
server_socket_udp=socket(AF_INET,SOCK_DGRAM,0);
server_address_udp.sin_family=AF_INET;
server_address_udp.sin_port=htons(6012);//6000转化为网络字节顺序
server_address_udp.sin_addr.S_un.S_addr=htons(INADDR_ANY);//将long转化为网络字节顺序 inet_addr("127.0.0.1");
if(SOCKET_ERROR==bind(server_socket_udp,(sockaddr *)(&server_address_udp),sizeof(server_address_udp)))
{
CString str;
str.Format("绑定Socket失败,错误代码:%d",GetLastError());
MessageBox(str);
closesocket(server_socket_udp);
return;
}
int len=sizeof(from_address_udp);
recvfrom(server_socket_udp,server_data,20,0,(sockaddr *)&(from_address_udp),&len);//但是接收不到数据,程序停在这里
客户端:
SOCKET consumer_udp;
sockaddr_in server_address_udp1;
char consumer_data[20];
consumer_udp=socket(AF_INET,SOCK_DGRAM,0);
server_address_udp1.sin_family=AF_INET;
server_address_udp1.sin_port=htons(6012);//199186转化为网络字节顺序
server_address_udp1.sin_addr.S_un.S_addr=htons(INADDR_BROADCAST);
sendto(consumer_udp,consumer_data,20,0,(sockaddr *)&server_address_udp1,sizeof(sockaddr));//可以发送成功
服务器端:
SOCKET server_socket_udp;
sockaddr_in server_address_udp,from_address_udp;
char server_data[20]="你好";
server_socket_udp=socket(AF_INET,SOCK_DGRAM,0);
server_address_udp.sin_family=AF_INET;
server_address_udp.sin_port=htons(6012);//6000转化为网络字节顺序
server_address_udp.sin_addr.S_un.S_addr=htons(INADDR_ANY);//将long转化为网络字节顺序 inet_addr("127.0.0.1");
if(SOCKET_ERROR==bind(server_socket_udp,(sockaddr *)(&server_address_udp),sizeof(server_address_udp)))
{
CString str;
str.Format("绑定Socket失败,错误代码:%d",GetLastError());
MessageBox(str);
closesocket(server_socket_udp);
return;
}
int len=sizeof(from_address_udp);
recvfrom(server_socket_udp,server_data,20,0,(sockaddr *)&(from_address_udp),&len);//但是接收不到数据,程序停在这里
客户端:
SOCKET consumer_udp;
sockaddr_in server_address_udp1;
char consumer_data[20];
consumer_udp=socket(AF_INET,SOCK_DGRAM,0);
server_address_udp1.sin_family=AF_INET;
server_address_udp1.sin_port=htons(6012);//199186转化为网络字节顺序
server_address_udp1.sin_addr.S_un.S_addr=htons(INADDR_BROADCAST);
sendto(consumer_udp,consumer_data,20,0,(sockaddr *)&server_address_udp1,sizeof(sockaddr));//可以发送成功