Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Open C 套接字: send, sendto, sendmsg 方法

From Wiki
Jump to: navigation, search
Article Metadata

文章
dougcn 在 24 Jun 2008 创建
最后由 hamishwillee 在 15 Dec 2011 编辑

Open C 套接字: send, sendto, sendmsg 方法

send,sendto,sendmsg方法用于从套接字发送消息。

ssize_t send (int s, const void *msg, size_t len, int flags);
 
ssize_t sendto (int s, const void *msg, size_t len, int flags, const struct sockaddr *to,
socklen_t tolen);
 
ssize_t sendmsg (int s, const struct msghdr *msg, int flags);

sendsendto以及sendmsg系统调用用于发送消息到另一个套接字。send函数在套接字处于连接状态时方可使用。

sendtosendmsg在任何时候都可使用。

下面的代码片段演示了sendsendtosendmsg函数的用法:

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Recv()
{
struct sockaddr_in serv_addr;
int sock_fd;
char line[15] = "Hello world!";
int size = 13;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
serv_addr.sin_port = htons(5000);
sock_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
connect(sock_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
send(sock_fd, line, size, 0);
close(sock_fd);
}
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Sendto()
{
sockaddr_in receiver_addr;
int sock_fd;
char line[15] = "Hello World!";
sock_fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
receiver_addr.sin_family = AF_INET;
receiver_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
receiver_addr.sin_port = htons(5000);
sendto(sock_fd, line, 13, 0,(struct sockaddr*)&receiver_addr,sizeof(receiver_addr));
close(sock_fd);
}


#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void sendmsg()
{
struct sockaddr_in receiver_addr;
int sock_fd;
char line[15] = "Hello World!";
struct msghdr msg;
struct iovec iov;
sock_fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
 
receiver_addr.sin_family = AF_INET;
receiver_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
receiver_addr.sin_port = htons(5000);
msg.msg_name = &receiver_addr;
msg.msg_namelen = sizeof(receiver_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_iov->iov_base = line;
msg.msg_iov->iov_len = 13;
msg.msg_control = 0;
msg.msg_controllen = 0;
msg.msg_flags = 0;
sendmsg(sock_fd,&msg,0);
close(sock_fd);
}

内部链接

Internal Links

This page was last modified on 15 December 2011, at 05:41.
237 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×