免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1854 | 回复: 0
打印 上一主题 下一主题

UDP编程入门 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-01-20 16:50 |只看该作者 |倒序浏览
udp函数:
头文件: #include  #include

int sendto(int sockfd, const void *msg,int len,unsigned int flags,const struct sockaddr *to, int tolen);
  该函数比send()函数多了两个参数,to表示目地机的IP地址和端口号信息,而tolen常常被赋值为sizeof (struct sockaddr)。Sendto 函数也返回实际发送的数据字节长度或在出现发送错误时返回-1。
 Recvfrom()函数原型为:
  int recvfrom(int sockfd,void *buf,int len,unsigned int flags,struct sockaddr *from,int *fromlen);
  from是一个struct sockaddr类型的变量,该变量保存源机的IP地址及端口号。fromlen常置为sizeof(struct sockaddr)。当recvfrom()返回时,fromlen包含实际存入from中的数据字节数。Recvfrom()函数返回接收到的字节数或当出现错误时返回-1,并置相应的errno。
以下为服务端程序:
#include
#include
#include
#include
#include
#include
#include
#include
#include
int port = 8888;
int main()
{
int sockfd;
int len;
int z;
char buf[256];
struct sockaddr_in adr_inet;
struct sockaddr_in adr_clnt;

printf("wait client.....\n");

adr_inet.sin_family = AF_INET;
adr_inet.sin_port = htons(port);
adr_inet.sin_addr.s_addr = htonl(INADDR_ANY);
bzero(&(adr_inet.sin_zero), 8);
len = sizeof(adr_clnt);

sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
{
  perror("create socket error");
  exit(1);
}
z = bind(sockfd, (struct sockaddr *)&adr_inet, sizeof(adr_inet));
if (z == -1)
{
  perror("bind error");
  exit(1);
}
while (1)
{
  z = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&adr_clnt, &len);
  if (z

以下为客户端程序:

#include
#include
#include
#include
#include
#include
#include
#include
#include
int port = 8888;

int main()
{
int sockfd;
int i = 0;
int z;

char buf[80], str1[80];
struct sockaddr_in adr_srvr;
FILE *fp;
printf("open file......\n");
fp = fopen("liu", "r");
if (fp == NULL)
{
  perror("open file error");  
  exit(1);
}
printf("connect serve.....\n");
adr_srvr.sin_family = AF_INET;
adr_srvr.sin_port = htons(port);
adr_srvr.sin_addr.s_addr = htonl(INADDR_ANY);
bzero(&(adr_srvr.sin_zero), 8);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
{
  perror("socket error");
  exit(1);
}
printf("send file.....\n");
for (i = 0; i
建立文件liu

打开一个终端:运行服务程序
[root@localhost net]# ./udp_s
wait client.....


打开另一个终端,运行客户端程序

[root@localhost net]# ./udp_c
open file......
connect serve.....
send file.....
0: hello linux
1: hello world
2: nice to me you
send ........
[root@localhost net]#
服务端显示:
[root@localhost net]# ./udp_s
wait client.....
receive: 0: hello linux
receive: 1: hello world
receive: 2: nice to me you
receive: stop
end........
[root@localhost net]#


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/86974/showart_2155100.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP