測試ipv6網路連通性的UDP協議測試程式碼
client.c
#include<sys/socket.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include <net/if.h> /* for ifconf */
#include <linux/sockios.h> /* for net status mask */
#include <netinet/in.h> /* for sockaddr_in */
#include <sys/types.h>
#include <sys/ioctl.h>
#define MAXLINE 80
#define SERV_PORT 8002
#define UDP_DATA_MAX_LEN (65535)
void do_cli(FILE*fp,int sockfd,struct sockaddr * pservaddr,socklen_t servlen)
{
int n;
char sendline[MAXLINE],recvline[MAXLINE+1];
/*connecttoserver*/
if(connect(sockfd,(struct sockaddr*)pservaddr,servlen)==-1)
{
perror("connect error");
exit(1);
}
else{
fputs("connect success\n",stdout);
}
while(fgets(sendline,MAXLINE,fp)!=NULL)
{
/*readalineandsendtoserver*/
write(sockfd,sendline,strlen(sendline));
/*receivedatafromserver*/
n=read(sockfd,recvline,MAXLINE);
if(n==-1)
{
perror("readerror");
exit(1);
}
recvline[n]=0;/*terminatestring*/
fputs(recvline,stdout);
fputs("lll",stdout);
}
}
int main(int argc,char **argv)
{
if(argc!=2)
{
printf("usage:udpclient\n");
exit(1);
}
int sockfd;
struct sockaddr_in6 sa6;
bzero(&sa6, sizeof(struct sockaddr_in6));
sa6.sin6_family=AF_INET6;
sa6.sin6_port=htons(SERV_PORT);
if(inet_pton(AF_INET6,argv[1],&sa6.sin6_addr)<=0)
{
printf("[%s]is not avalid IPaddress\n",argv[1]);
exit(1);
}
sockfd=socket(AF_INET6,SOCK_DGRAM,0);
//sockfd = init_socket(&sa6);
do_cli(stdin,sockfd,(struct sockaddr*)&sa6,sizeof(sa6));
return 0;
}
sever.c
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <poll.h>
#include <net/if.h>
#include <unistd.h>
#include <netdb.h>
#include <ctype.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/select.h>
#include<sys/socket.h> /* for ifconf */
#include <linux/sockios.h> /* for net status mask */ /* for sockaddr_in */
#include <sys/ioctl.h>
#define MAXLINE 80
#define SERV_PORT 8002
#define UDP_DATA_MAX_LEN (65535)
void do_echo(int sockfd,struct sockaddr* pcliaddr,socklen_t clilen)
{
int n;
socklen_t len;
char mesg[MAXLINE];
for(;;)
{
len=clilen;
memset(mesg,0,sizeof(mesg));
/*waitingforreceivedata*/
n=recvfrom(sockfd,mesg,MAXLINE,0,pcliaddr,&len);
fputs(mesg,stdout);
/*sentdatabacktoclient*/
sendto(sockfd,mesg,n,0,pcliaddr,len);
}
}
int main(int argc,char* argv[])
{
int sockfd;
struct sockaddr_in6 servaddr,cliaddr;
/*init servaddr*/
bzero(&servaddr,sizeof(servaddr));
servaddr.sin6_addr = in6addr_any;
servaddr.sin6_port = htons(8002);
servaddr.sin6_family = AF_INET6;
/*bind address and port to socket*/
sockfd=socket(AF_INET6,SOCK_DGRAM,0);/*create a socket*/
if(bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr))==-1)
{
perror("binderror");
exit(1);
}
do_echo(sockfd,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
return 0;
}