//服务器:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define N 100
typedef struct sockaddr SA;
int main(int argc,char **argv)
{
int sockfd;
socklen_t peerlen;
struct sockaddr_in myaddr,peeraddr;
char buf[N];
if((sockfd = socket(PF_INET,SOCK_DGRAM,0))<0)
{
perror("fail to socket");
exit(-1);
}
bzero(&myaddr,sizeof(myaddr));
myaddr.sin_family =PF_INET;
myaddr.sin_addr.s_addr =inet_addr("192.168.0.21");//服务器地址
myaddr.sin_port =htons(8888);
if(bind(sockfd,(SA*)&myaddr,sizeof(myaddr))<0)
{
perror("fail to blind");
exit(-1);
}
for(;;)
{
peerlen = sizeof(peeraddr);
recvfrom(sockfd,buf,sizeof(buf),0,(SA*)&peeraddr,&peerlen);
printf("connection form %s,port%d/n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port));
sendto(sockfd,buf,sizeof(buf),0,(SA*)&peeraddr,sizeof(peeraddr));
}
return 0;
}
//客户端:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define N 100
typedef struct sockaddr SA;
int main(int argc,char **argv)
{
int sockfd;
socklen_t peerlen;
struct sockaddr_in servaddr;
char buf[N];
if((sockfd = socket(PF_INET,SOCK_DGRAM,0))<0)
{
perror("fail to socket");
exit(-1);
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family =PF_INET;
servaddr.sin_addr.s_addr =inet_addr("192.168.0.21");
servaddr.sin_port =htons(8888);
printf("send what?/n");
scanf("%s",&buf);
sendto(sockfd,buf,sizeof(buf),0,(SA*)&servaddr,sizeof(servaddr));
bzero(buf,sizeof(buf));
recvfrom(sockfd,buf,N,0,NULL,NULL);
printf("recv from server:%s/n",buf);
return 0;
}