查看文章
 
udp 服务器程序(最简单版)
2011年09月26日 星期一 12:25

include <stdio.h>

#include <stdlib.h>

#include <errno.h>

#include <string.h>

#include <sys/types.h>

#include <netinet/in.h>

#include <sys/socket.h>

#include <sys/wait.h>

#define MYPORT 3490 /* 监听端口 */

 

void main()

{

int sockfd; /* 数据端口 */

struct sockaddr_in my_addr; /* 自身的地址信息 */

struct sockaddr_in their_addr; /* 连接对方的地址信息 */

int sin_size, retval;

char buf[128];

 

if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {

perror("socket");

exit(1);

}

 

my_addr.sin_family = AF_INET;

my_addr.sin_port = htons(MYPORT); /* 网络字节顺序 */

my_addr.sin_addr.s_addr = INADDR_ANY; /* 自动填本机IP */

bzero(&(my_addr.sin_zero), 8); /* 其余部分置0 */

 

if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) == -1) {

perror("bind");

exit(1);

}

 

/* 主循环 */

while(1) { 

retval = recvfrom(sockfd, buf, 128, 0, (struct sockaddr *)&their_addr, &sin_size);

printf("Received datagram from %s\n",inet_ntoa(their_addr.sin_addr));

if (retval == 0) {

perror (“recvfrom");

close(sockfd);

break;

}

retval = sendto(sockfd, buf, 128, 0, (struct sockaddr *)&their_addr, sin_size);

}

}

 

转自:http://www.aka.org.cn/Lectures/002/Lecture-2.1.8/Lecture-2.1.8/new_page_33.htm


类别:计算机通信||添加到搜藏 |分享到i贴吧|浏览(41)|评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
     

   
帮助中心 | 空间客服 | 投诉中心 | 空间协议
©2012 Baidu