server.c--------------------->服务器端
//./server ip port
int main(int argc, const char *argv[])
{
int sockfd;
int n;
char buf[1024];
struct sockaddr_in server_addr,peer_addr;
int addr_len = sizeof(struct sockaddr);
sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(sockfd < 0){
perror("Fail to socket");
exit(EXIT_FAILURE);
}
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[2]));
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
while(1)
{
printf(">");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf) - 1] = '\0';
sendto(sockfd,buf,strlen(buf),0,(struct sockaddr *)&server_addr,addr_len);
n = recvfrom(sockfd,buf,sizeof(buf) - 1,0,(struct sockaddr *)&peer_addr,&addr_len);
buf[n] = '\0';
printf("***********************\n");
printf("Ip:%s.\n",inet_ntoa(peer_addr.sin_addr));
printf("Port:%d.\n",ntohs(peer_addr.sin_port));
printf("Buf:%s.\n",buf);
printf("***********************\n");
}
exit(EXIT_SUCCESS);;
}
client.c--------------------->客户端
//./server ip port
int main(int argc, const char *argv[])
{
int sockfd;
int n;
char buf[1024];
struct sockaddr_in server_addr,peer_addr;
int addr_len = sizeof(struct sockaddr);
// 创建流式套接字
sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(sockfd < 0){
perror("Fail to socket");
exit(EXIT_FAILURE);
}
//设置服务器的ip和port
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[2]));
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
while(1)
{
printf(">");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf) - 1] = '\0';
//发送
sendto(sockfd,buf,strlen(buf),0,(struct sockaddr *)&server_addr,addr_len);
//接受
n = recvfrom(sockfd,buf,sizeof(buf) - 1,0,(struct sockaddr *)&peer_addr,&addr_len);
buf[n] = '\0';
printf("***********************\n");
printf("Ip:%s.\n",inet_ntoa(peer_addr.sin_addr));
printf("Port:%d.\n",ntohs(peer_addr.sin_port));
printf("Buf:%s.\n",buf);
printf("***********************\n");
}
exit(EXIT_SUCCESS);;
}
阅读(2310) | 评论(0) | 转发(0) |