熟悉UDP客户端服务器编程
?
1、实现UDP客户端服务器回显程序
2、传输信息要求如下
(1)尝试用C语言结构去发送或接收一个信息包
(2)将服务器运行于开发板,客服端运行于ubuntu 12.04,抓包分析UDP协议
?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
?
#define PORT 1234
#define BACKLOG 1
?
int main()
{
int listenfd, connectfd;
struct sockaddr_in server;
struct sockaddr_in client;
socklen_t addrlen;
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("Creating socket failed.");
exit(1);
}
int opt =SO_REUSEADDR;
setsockopt(listenfd,SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr= htonl (INADDR_ANY);
if(bind(listenfd, (struct sockaddr *)&server, sizeof(server)) == -1) {
perror("Binderror.");
exit(1);
}
if(listen(listenfd,BACKLOG)== -1){ /* calls listen() */
perror("listen()error\n");
exit(1);
}
addrlen =sizeof(client);
if((connectfd = accept(listenfd,(struct sockaddr*)&client,&addrlen))==-1) {
perror("accept()error\n");
exit(1);
}
printf("Yougot a connection from cient‘s ip is %s, prot is %d\n",inet_ntoa(client.sin_addr),htons(client.sin_port));
send(connectfd,"Welcometo my server.\n",22,0);
close(connectfd);
close(listenfd);
return 0;
}
?
?
????2、在客户端传送信息,并接收回显结果
?
#include<stdio.h>
#include <stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
?
#define PORT 1234
#define MAXDATASIZE 100
?
int main(int argc, char *argv[])
{
int sockfd, num;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in server;
if (argc!=2) {
printf("Usage:%s <IP Address>\n",argv[0]);
exit(1);
}
if((he=gethostbyname(argv[1]))==NULL){
printf("gethostbyname()error\n");
exit(1);
}
if((sockfd=socket(AF_INET, SOCK_STREAM, 0))==-1){
printf("socket()error\n");
exit(1);
}
bzero(&server,sizeof(server));
server.sin_family= AF_INET;
server.sin_port = htons(PORT);
server.sin_addr =*((struct in_addr *)he->h_addr);
if(connect(sockfd,(struct sockaddr *)&server,sizeof(server))==-1){
printf("connect()error\n");
exit(1);
}
if((num=recv(sockfd,buf,MAXDATASIZE,0)) == -1){
printf("recv() error\n");
exit(1);
}
buf[num-1]=‘\0‘;
printf("Server Message: %s\n",buf);
close(sockfd);
return 0;
}
3、在服务器接收客服端信息,显示并回显
?
????4、交叉编译服务器,并通过NFS共享拷贝到开发板运行
?
5、编译客服端,直接在ubuntu 12.04上运行
?
6、测试客户端与服务器能正常通过UDP传输信息
?
实验心得:
????UDP是一种基于无连接的通信方式,该实验里,实现了一个服务器端:开发板,和一个客户端pc主机。两者进行信息的交流。上面是我的实现的截图。整个过程很是顺利。谢谢。
原文:http://www.cnblogs.com/FORFISH/p/4201834.html