初学socket编程,想写一个简单的udp包分析程序,可是现在在接受时就遇到了问题。程序代码如下所示。这个程序段能够通过编译,可是编译后的结果为创建套接字成功,绑定端口成功就直接退出了。多次调试发现此程序能进入了*recv_message函数,在leng = recvfrom(sock, buffer, sizeof(buffer), 0,(struct sockaddr *)&server_addr, &addr_len)<0这句之前没有问题,可是之后就没有反应了,请论坛内的高人给予指点这是个什么情况,以及如何解决,不胜感激!!!!
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define UDP_PORT 14460
#define SERVER_PORT 15380
volatile struct sockaddr_in client_addr;
int res=0;
int sock;
pthread_t recv_thread,code_thread;
sem_t send_sem;
struct sockaddr_in server_addr;
socklen_t addr_len = sizeof(server_addr);
char send_message_buffer[40];
char buffer[40];
void *recv_message(void *arg)
{
int leng;
while(1)
{
if (leng = recvfrom(sock, buffer, sizeof(buffer), 0,(struct sockaddr *)&server_addr, &addr_len)<0);//到这就木有反应了。。。。
// leng < 0)
{
printf("接收数据失败");
}
}
}
int main(int argc, char **argv)
{
int len;
pthread_attr_t thread_attr;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
exit(0);
}
else
{
printf("创建套接字成功\n");
}
memset(&server_addr, 0, sizeof(struct sockaddr_in));
/* 设置地址和端口信息 */
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = htons(INADDR_ANY);//inet_addr("192.168.0.103");
/* 绑定地址和端口信息 */
if ((bind(sock, (struct sockaddr *) &server_addr, addr_len)) == -1)
{
printf("绑定端口error\n");exit(1);
}
else
{
printf("绑定端口成功\n");
}
client_addr.sin_addr.s_addr = inet_addr("192.168.0.100");
client_addr.sin_port = htons(UDP_PORT);
if(res!=0)
{
exit(EXIT_FAILURE);
}
/* if(connect(socket,(struct sockaddr *)&server_addr,sizeof(client_addr))==-1)
{
printf("connect failed!\n");
exit(0);
}
else
printf("connect successed!\n");*/
res=pthread_attr_init(&thread_attr); //设置属性为脱离状态
if(res!=0)
{
exit(1);
}
res=pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED);//设置属性为脱离状态::即不等待子线程的返回值--子线程终止?
if(res!=0)
{
exit(1);
}
while(1)
{
res=pthread_create(&recv_thread,&thread_attr,recv_message,NULL); //调用接收函数
if(res!=0)
{
exit(1);
}
}
return 0;
}