即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

udp采用sendmsg发送消息失败

编程语言 u010643777 16℃ 0评论
本文目录
[隐藏]

本人最近在学习socket程序的编写,使用sendmsg向外发送数据,但是接收端不能接收数据。代码是这样的:

#include
#include
#include  //  ntohs   inet_ntoa
#include
#include
#define MAX_LEN 100
static char *server="127.0.0.1";
static int port=1234;

int parser_sender(struct sockaddr_in *addr,char *buf,int len)
{
 printf("recv packet from %s  %d\n",inet_ntoa(addr->sin_addr),ntohs(addr->sin_port));
 printf("recv msg %s\n",buf);
}
int main()
{
 char send[] = "hello yuna";
 char buffer[MAX_LEN];
 int fd;
 int nrec;
 struct sockaddr_in serv_socket,from;
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    bzero(&serv_socket, sizeof(serv_socket));
    serv_socket.sin_family = AF_INET;
    serv_socket.sin_port = htons(port);
    inet_pton(AF_INET, server, &serv_socket.sin_addr);
 
    struct msghdr msg;
 //bzero(&msg,sizeof(struct msghdr));
    msg.msg_name = &serv_socket;
    msg.msg_namelen = sizeof(struct sockaddr_in);
    struct iovec io;
    io.iov_base = send;
    io.iov_len = sizeof(send);
    msg.msg_iov = &io;
    msg.msg_iovlen = 1;
    ssize_t send_size = sendmsg(fd, &msg, 0);
 
 msg.msg_name =&from;
 msg.msg_namelen =sizeof(struct sockaddr_in);
 io.iov_base =buffer;
    io.iov_len =MAX_LEN;
 
 nrec=recvmsg(fd,&msg,0);
 parser_sender(&from,buf,nrec);

}


这是因为msg中的msg_control可能指向垃圾内存,解决办法就是加上注释掉的代码,将msg中的内存置零。至于为什么会出现这种情况,在此记录,等以后明白了,再续。


1. 参考:error in sendmsg() call in linux c





转载请注明:CodingBlog » udp采用sendmsg发送消息失败

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情