分类: LINUX
2011-06-22 10:52:51
/*
* UDP服务端程序设计
* 给客户端发送当前系统时间
* lzy 2011-6-22
*/
#include
#include
#include
#include
#include
#include
#include
#define SERV_PORT 5555 //服务器接听端口号
#define BACKLOG 20 //请求队列中允许请求数
#define BUF_SIZE 256 //缓冲区大小
int main(void)
{
int ret;
char buf[BUF_SIZE];
pid_t pid; //定义管道描述符
int sockfd; //定义sock描述符
int clientfd; //定义数据传输sock描述符
struct sockaddr_in host_addr; //本机IP地址和端口信息
struct sockaddr_in client_addr; //客户端IP地址和端口信息
int length = sizeof client_addr;
/**创建套接字**/
sockfd = socket(AF_INET, SOCK_DGRAM, 0); //TCP/IP协议,数据流套接字
if(sockfd == -1)
{
perror("socket");
exit(0);
}
/**绑定套接字**/
bzero(&host_addr, sizeof host_addr);
host_addr.sin_family = AF_INET; //TCP/IP协议
host_addr.sin_port = htons(SERV_PORT); //设定端口号
host_addr.sin_addr.s_addr = INADDR_ANY; //本地IP地址
ret = bind(sockfd, (struct sockaddr *)&host_addr, sizeof host_addr); //绑定套接字
if(ret == -1)
{
perror("bind");
exit(0);
}
while(1)
{
bzero(buf, sizeof buf);
ret = recvfrom(sockfd, buf, sizeof(buf), 0 ,(struct sockaddr *)&client_addr, &length);//接收接连请求
if(ret == -1)
{
perror("accept");
exit(0);
}
printf("Client IP:%s \n", inet_ntoa(client_addr.sin_addr.s_addr)); //输出客户端IP
printf("Received: %s\n", buf);
sleep(2);
}
close(clientfd);
return 0;
}
/*
* TCP客户端程序设计
* 读取服务器发送的信息
* lzy 2011-6-22
*/
#include
#include
#include
#include
#include
#include
#include
#include
#define SERV_PORT 5555 //服务器接听端口号
#define BACKLOG 20 //请求队列中允许请求数
#define BUF_SIZE 256 //缓冲区大小
int main(int argc, char *argv[])
{
int ret;
time_t tt;
struct tm *ttm;
char buf[BUF_SIZE];
int sockfd; //定义sock描述符
struct sockaddr_in serv_addr; //服务器IP地址和端口信息
if(argc != 2)
{
printf("命令行输入有误\n"); //命令行带IP
exit(0);
}
/**创建套接字**/
sockfd = socket(AF_INET, SOCK_DGRAM, 0); //TCP/IP协议,数据流套接字
if(sockfd == -1)
{
perror("socket");
exit(0);
}
/**建立连接**/
bzero(&serv_addr, sizeof serv_addr);
serv_addr.sin_family = AF_INET; //TCP/IP协议
serv_addr.sin_port = htons(SERV_PORT); //设定端口号
//serv_addr.sin_addr.s_addr = INADDR_ANY; //使用回环地址 127.0.0.1
inet_aton(argv[1], (struct sockaddr *)&serv_addr.sin_addr.s_addr); //设定IP地址
while(1)
{
bzero(buf, sizeof buf);
tt = time(NULL);
ttm = localtime(&tt);
strcpy(buf, asctime(ttm));
sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&serv_addr, sizeof serv_addr); //接收数据
sleep(2);
}
close(sockfd);
return 0;
}