欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Linux UDP服务端客户端程序

程序员文章站 2022-03-04 08:46:14
...

服务端

#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<arpa/inet.h>

#define PORT 1234
#define MAXDATASIZE 100

main()
{
   int sockfd;
   struct sockaddr_in server;
   struct sockaddr_in client;
   socklen_t addrlen;
   int num;
   char buf[MAXDATASIZE];

   if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
   {
	   perror("Creatingsocket failed.");
	   exit(1);
   }

   bzero(&server,sizeof(server));
   server.sin_family=AF_INET;
   server.sin_port=htons(PORT);
   server.sin_addr.s_addr= htonl (INADDR_ANY);
   if(bind(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1)
   {
	   perror("Bind()error.");
	   exit(1);
   }   

   addrlen=sizeof(client);
   while(1)  
   {
		num =recvfrom(sockfd,buf,MAXDATASIZE,0,(struct sockaddr*)&client,&addrlen);                                   

   if (num < 0)
   {
	   perror("recvfrom() error\n");
	   exit(1);
   }

	   buf[num] = '\0';
	   printf("You got a message (%s%) from client.\nIt's ip is%s, port is %d.\n",buf,inet_ntoa(client.sin_addr),htons(client.sin_port)); 
	   sendto(sockfd,"Welcometo my server.\n",22,0,(struct sockaddr *)&client,addrlen);
	   if(!strcmp(buf,"bye"))
	   break;
   }
   close(sockfd);  
}

//客户端

#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,peer;

	if (argc !=3)
	{
		printf("Usage: %s <IP Address><message>\n",argv[0]);
		exit(1);
	}

	if ((he=gethostbyname(argv[1]))==NULL)
	{
		printf("gethostbyname()error\n");
		exit(1);
	}

	if ((sockfd=socket(AF_INET, SOCK_DGRAM,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);
	sendto(sockfd, argv[2],strlen(argv[2]),0,(struct sockaddr *)&server,sizeof(server));
	socklen_t  addrlen;
	addrlen=sizeof(server);
	while (1)
	{
	if((num=recvfrom(sockfd,buf,MAXDATASIZE,0,(struct sockaddr *)&peer,&addrlen))== -1)
	{
		printf("recvfrom() error\n");
		exit(1);
	}
	if (addrlen != sizeof(server) ||memcmp((const void *)&server, (const void *)&peer,addrlen) != 0)
	{
		printf("Receive message from otherserver.\n");
		continue;
	}

	buf[num]='\0';
	printf("Server Message:%s\n",buf);
	break;
	}

	close(sockfd);
}

//示例
./client 127.0.0.1 hello
./server

相关标签: Linux系统编程